字符串全复制
/* strcpy example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[]="Sample string";
char str2[40];
char str3[40];
strcpy (str2,str1);
strcpy (str3,"copy successful");
printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
return 0;
}
str1:示例字符串
str2:示例字符串
str3:复制成功
字符串半复制
/* strncpy example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[]= "To be or not to be";
char str2[40];
char str3[40];
/* copy to sized buffer (overflow safe): */
strncpy ( str2, str1, sizeof(str2) );
/* partial copy (only 5 chars): */
strncpy ( str3, str2, 5 );
str3[5] = '\0'; /* null character manually added */
puts (str1);
puts (str2);
puts (str3);
return 0;
}
To be or not to be
To be or not to be
To be
字符串连接
/* strcat example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[80];
strcpy (str,"these ");
strcat (str,"strings ");
strcat (str,"are ");
strcat (str,"concatenated.");
puts (str);
return 0;
}
these strings are concatenated.
字符串按字节比较
/* memcmp example */
#include <stdio.h>
#include <string.h>
int main ()
{
char buffer1[] = "DWgaOtP12df0";
char buffer2[] = "DWGAOTP12DF0";
int n;
n=memcmp ( buffer1, buffer2, sizeof(buffer1) );
if (n>0) printf ("'%s' is greater than '%s'.\n",buffer1,buffer2);
else if (n<0) printf ("'%s' is less than '%s'.\n",buffer1,buffer2);
else printf ("'%s' is the same as '%s'.\n",buffer1,buffer2);
return 0;
}
“DWgaOtP12df0”大于“DWGAOTP12DF0”。
因为DWgAOtp12Df0大于DWGAOTP12DF0,因为两个单词中的第一个不匹配字符分别是“g”和“G”,并且“g”(103)的计算结果大于“G”(71)。
返回值 | 表示 |
---|---|
<0 | 两个内存块中不匹配的第一个字节在ptr1中的值低于ptr2中的值 |
0 | 两个内存块的内容相等 |
>0 | 两个内存块中不匹配的第一个字节在ptr1中的值大于在ptr2中的值 |
与strcmp不同,该函数在找到空字符后不会停止比较。
字符串长度计算
/* strlen example */
#include <stdio.h>
#include <string.h>
int main ()
{
char szInput[256]={'a','b','c'};
printf ("The sentence entered is %u characters long.\n",(unsigned)strlen(szInput));
return 0;
}
The sentence entered is 3 characters long.
strlen()返回值是字符串长度,而非数组下标
字符匹配
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "This is a sample string";
char * pch;
printf ("Looking for the 's' character in \"%s\"...\n",str);
pch=strchr(str,'s');
while (pch!=NULL)
{
printf ("found at %d\n",pch-str+1);
pch=strchr(pch+1,'s')
/*从pch开始往后找,找到‘s’第一次出现的位置 若找不到,返回空指针*/
/*位置从1开始计算*/
}
return 0;
}
Looking for the ‘s’ character in “This is a sample string”…
found at 4
found at 7
found at 11
found at 18
字符串匹配
/* strstr example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="This is a simple string";
char * pch;
pch = strstr (str,"simple");
if (pch != NULL)
strncpy (pch,"sample",6);
puts (str);
return 0;
}
This is a sample string
此示例在str中 搜索“simple”子字符串并将该单词替换为“sample”。
若需要匹配多次,可类比《字符匹配》