欢迎访问宙启技术站
智能推送

10个常见字符串函数及使用方法

发布时间:2023-12-07 17:20:59

1. strlen(string):返回字符串的长度

使用方法:

char str[50] = "Hello, world!";
int len = strlen(str);
// len的值为12

2. strcpy(dest, source):将source字符串复制到dest字符串

使用方法:

char str1[50] = "Hello";
char str2[50];
strcpy(str2, str1);
// str2的值为"Hello"

3. strcat(dest, source):将source字符串追加到dest字符串的末尾

使用方法:

char str1[50] = "Hello";
char str2[] = " world!";
strcat(str1, str2);
// str1的值为"Hello world!"

4. strcmp(str1, str2):比较str1和str2字符串的大小

使用方法:

char str1[] = "apple";
char str2[] = "banana";
int result = strcmp(str1, str2);
// result的值为-1,表示str1在字典序中小于str2

5. strchr(str, ch):在str字符串中查找字符ch的第一次出现位置,返回指向该位置的指针

使用方法:

char str[50] = "Hello, world!";
char* ptr = strchr(str, 'o');
// ptr指向str字符串中第一个'o'的位置

6. strstr(str, substr):在str字符串中查找substr字符串的第一次出现位置,返回指向该位置的指针

使用方法:

char str[50] = "Hello, world!";
char* ptr = strstr(str, "world");
// ptr指向str字符串中"world"的位置

7. atoi(str):将字符串str转换为整数

使用方法:

char str[] = "123";
int num = atoi(str);
// num的值为123

8. atof(str):将字符串str转换为浮点数

使用方法:

char str[] = "3.14";
float num = atof(str);
// num的值为3.14

9. isalpha(ch):判断字符ch是否为字母

使用方法:

char ch = 'A';
if (isalpha(ch))
{
    // ch是字母
}

10. isdigit(ch):判断字符ch是否为数字

使用方法:

char ch = '9';
if (isdigit(ch))
{
    // ch是数字
}

以上是常见的10个字符串函数及其使用方法。这些函数在不同的编程语言中也有类似的实现,可以根据具体的语言来进行使用。