String 是一个以特殊 null 结尾的字符 '\0' 结尾的字符序列。如果没有\0,则在找到\0 符号之前,使用字符串的函数不会停止。此字符可能出现在 pseudo 字符串(我的意思是没有\0 的字符串)结尾之后的任何位置,然后才停止。
下面的例子说明了这个空终止字符的必要性:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char string[] = "Hello!";
printf("original string:\n%s\n\n", string);
memset(string, '-', 5);
printf("memset doesn't affect the last two symbols: '!' and '\\0':\n%s", string);
memset(string, '-', 6);
printf("\n\nmemset doesn't affect the last symbol: '\\0':\n%s\n\n", string);
memset(string, '-', 7);
printf("memset affects all symbols including null-terminated one:\n%s", string);
return 0;
}
/* OUTPUT:
original string:
Hello!
memset doesn't affect the last two characters: '!' and '\0':
-----!
memset doesn't affect the last character: '\0':
------
memset affects all characters including null-terminated one:
-------@↓@
*/
Substring 是字符串中的字符序列。它可能小于或等于字符串。
假设,"NaOH" 是一个字符串。那么子字符串可能是:"N"、"a"、"O"、"H"、"Na"、"aO"、"OH"、"NaO"、"aOH"、"NaOH"。要查找子字符串是否在字符串中,您可以使用strstr 函数。它的原型是char * strstr ( char * str1, const char * str2 );。
这段代码显示了这个函数的结果:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *ptrCh = NULL;
ptrCh = strstr("hello", "h");
printf("ptrCh: %p\n", ptrCh);
printf("%s\n\n", ptrCh);
ptrCh = strstr("hello", "z");
printf("ptrCh: %p\n", ptrCh);
printf("%s\n\n", ptrCh);
return 0;
}
/* OUTPUT:
ptrCh: 00403024
hello
ptrCh: 00000000
(null)
*/
对于第一个printf,它从'h'的位置开始打印字符,当它到达'o'之后的下一个以null结尾的字符时,它就停止了,就像前面的程序一样。
为了使您的程序更具交互性,您可以声明数组,然后声明一个指向它的指针。数组大小必须足以存储最长的公式。假设,100 就足够了:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char buf[100] = {0};
char *ptr = &buf[0];
scanf("%s", ptr);
// printf() gets a pointer as argument
printf("%s\n", ptr);
// printf() gets also a pointer as argument.
// When you pass arrays name without index to a function,
// you pass a pointer to array's first element.
printf("%s", buf);
return 0;
}
而至于重写个字母在字符串的末尾。这是一个小程序。关注cmets:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char buf[100] = {0};
char formula[100] = {0};
char compound[100] = {0};
char *ptr = &buf[0];
char *pFormula = &formula[0];
char *pCompound = &compound[0];
printf("Enter formula: ");
scanf("%s", pFormula);
printf("Enter chemical compound: ");
scanf("%s", pCompound);
// Copying the first chemical elements without the last
// several that will be replaced by another elements.
strncpy(ptr, pFormula, strlen(pFormula) - strlen(pCompound));
// Adding new compound to the first elements.
// Function also adds a null-terminated character to the end.
strncat(ptr, pCompound, strlen(pCompound));
printf("The new chemical compound is: ");
printf("%s", ptr);
return 0;
}
/* OUTPUT:
Enter formula: NaOH
Enter chemical compound: Cl
The new chemical compound is: NaCl
*/