c string类的常用方法
在C语言中,字符串通常表示为字符数组,而不是像C++那样有专门的字符串类。但C标准库中提供了一些用于操作和处理字符串的函数。以下是其中的一些常用方法:
1. strcpy():将一个字符串复制到另一个字符串。
```c
char str1[50];
strcpy(str1, "Hello, World!");
```
2. strcat():将一个字符串连接到另一个字符串的末尾。
```c
char str1[50] = "Hello, ";
strcat(str1, "World!");
```
3. strlen():返回字符串的长度,不包括终止字符'\0'。
```c
char str[] = "Hello, World!";
printf("%d", strlen(str));  // 输出 13
```
4. strcmp():比较两个字符串。
```c
char str1[] = "Hello";
char str2[] = "World";
if (strcmp(str1, str2) < 0) {
    printf("%s is less than %s\n", str1, str2);
} else if (strcmp(str1, str2) > 0) {
    printf("%s is greater than %s\n", str1, str2);
} else {
    printf("%s is equal to %s\n", str1, str2);
}
```
5. strstr():在字符串中查子串。
```c
char str[] = "Hello, World!";
char sub[] = "World";
char result = strstr(str, sub);
if (result != NULL) {
    printf("Found '%s' in '%s'\n", sub, str);
} else {
    printf("Did not find '%s' in '%s'\n", sub, str);
}
```
6. sprintf():将格式化的数据写入字符串。
```c
char str[50];
int a = 10;
float b = ;
sprintf(str, "Integer: %d, Float: %f", a, b);
printf("%s\n", str);  // 输出 "Integer: 10, Float: "
strcmp比较数组```
7. tolower() / toupper():将字符转换为小写或大写。
这些是C语言中处理字符串的一些基本方法。当然,还有许多其他函数可用于更复杂的操作,如分割字符串、查和替换子串等。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。