总结C语言学习字符串时常用的函数

1.确定字符串的长度

strlen_s函数返回字符串的长度,它需要两个参数:字符串的地址(一维char数组的数组名),数组的大小。

for(unsigned int i = 0;i < strCount;++i)
{
    
    
	printf("The string is:\n%s contains %zu characters.\n",str[i],strlen_s(str[i],sizeof(str[i])));
}

2.复制字符串

strcpy_s函数可以把一个字符串变量赋予给另一个字符串。它的第一个参数指定为复制目标,第二个参数是一个整数,指定第一个参数的大小,第三个参数是源字符串。指定目标字符串的长度,可以使函数避免覆盖目标字符串中最后一个字符后面的内存。
注意:标准的复制函数使strcpy,它会把第二个函数指定的字符串复制到第一个参数指定的位置上,不检查目标字符串的容量。

char souce[] = "Hello";
char str[10];
if(strcpy_s(destination,sizeof(destination),sorce))
	printf("error!");

3.连接字符串

strcat_s可以把字符串复制到另一个字符串的末尾。它需要三个参数:要添加新字符串的地址,第一个参数可以储存最大字符串的长度,要添加的第一个参数的字符串地址。

#define __STDC_WANT_LIT_EXT1__1   
#include<string.h>
#include<stdio.h>

int main()
{
    
    
    char preamble[] = "The joke is:\n\n";
    char str[][40] = {
    
    "hello\n","world\n","you\n"};
    unsigned int strCount = sizeof(str)/sizeof(str[0]);//计算字符串的大小
    unsigned int length = 0;

    for (unsigned i = 0; i < strCount; i++)
        length += strnlen(str[i],sizeof(str[i]));              

    char joke[length + strnlen(preamble,sizeof(preamble))+1];//+1给/0留下了空间

    if(strncpy_s(joke,sizeof(joke),preamble,sizeof(preamble)))
    {
    
    
        printf("Errror copying preamble to joke.\n");
        return 1;
    }

    for(unsigned int i = 0; i < strCount ; ++i)
    {
    
    
        if(strncat_s(joke,sizeof(joke),str[i],sizeof(str[i])))
        {
    
    
            printf("Error copyong string str[%u].",i);
            return 2;
        }
    }
    printf("%s",joke);

    getchar();
    getchar();
    return 0;
}

4.比较字符串

strcmp(str1,str2)比较两个字符串,返回一个小于0,等于或大于0的int值,分别对应str1小于,等于和大于str2.

5.搜索字符串

strchr()在字符串中搜索给定的字符,它的第一个参数是要搜索的字符串(char数组的地址),第二个参数是要查找的字符。
strstr()在字符串中查找子字符串。第一个参数是要搜索的字符串,第二个参数是要查找的子字符串。

#include<stdio.h>
#include<string.h>

int main(void)
{
    
    
    char str1[] = "This string comtains the holy grail.";
    char str2[] = "the holy grail";
    char str3[] = "the holy grall";

    if(strstr(str1,str2))
    printf("\"%s\"was found in \"%s\"\n",str1,str2);
    else
    printf("\n\"%s\"was not found.",str2);

    if(!strstr(str1,str3))
    printf("\"%s\"was not found.\n",str3);
    else
    printf("\nWe shouldn't get to here!");

    getchar();
    getchar();
    return 0;
}

6.单元化字符串

strtok()的函数,来单元化字符串。它需要两个参数:要单元化的字符串,和包含所有可能的界定符的字符串。strtok_s()函数需要四个参数工作更安全,需要四个参数str,str_size,deliniters,pptr。

猜你喜欢

转载自blog.csdn.net/weixin_51871724/article/details/112234736