C语言中的字符串操作方法有哪些

发布时间:2022-03-30 13:33:14 作者:iii
来源:亿速云 阅读:237

C语言中的字符串操作方法有哪些

目录

  1. 引言
  2. 字符串的基本概念
  3. 字符串的声明与初始化
  4. 字符串的输入与输出
  5. 字符串的长度
  6. 字符串的复制
  7. 字符串的连接
  8. 字符串的比较
  9. 字符串的查找
  10. 字符串的截取
  11. 字符串的替换
  12. 字符串的转换
  13. 字符串的分割
  14. 字符串的格式化
  15. 字符串的其他操作
  16. 总结

引言

C语言是一种广泛使用的编程语言,尤其在系统编程和嵌入式开发中占有重要地位。字符串操作是C语言编程中的一个重要部分,掌握字符串的各种操作方法对于编写高效、可靠的程序至关重要。本文将详细介绍C语言中常见的字符串操作方法,帮助读者更好地理解和应用这些技术。

字符串的基本概念

在C语言中,字符串是由字符组成的数组,以空字符'\0'结尾。字符串的每个字符都是一个char类型的变量,存储在连续的内存地址中。由于字符串以'\0'结尾,因此可以通过遍历字符数组直到遇到'\0'来确定字符串的长度。

字符串的声明与初始化

在C语言中,字符串可以通过多种方式声明和初始化。

1. 使用字符数组

char str[] = "Hello, World!";

这种方式会在编译时自动在字符串末尾添加'\0'

2. 使用指针

char *str = "Hello, World!";

这种方式将字符串常量存储在只读内存中,指针str指向该字符串的首地址。

3. 手动初始化

char str[14] = {'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0'};

这种方式需要手动添加'\0'

字符串的输入与输出

1. 使用printfscanf

char str[100];
printf("Enter a string: ");
scanf("%s", str);
printf("You entered: %s\n", str);

scanf函数会读取输入直到遇到空白字符(空格、制表符、换行符等),并将其存储在str中。

2. 使用getsputs

char str[100];
printf("Enter a string: ");
gets(str);
printf("You entered: ");
puts(str);

gets函数会读取整行输入,直到遇到换行符,并将其存储在str中。puts函数用于输出字符串并自动添加换行符。

3. 使用fgetsfputs

char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("You entered: ");
fputs(str, stdout);

fgets函数会读取指定数量的字符或直到遇到换行符,并将其存储在str中。fputs函数用于输出字符串,不会自动添加换行符。

字符串的长度

1. 使用strlen函数

#include <string.h>

char str[] = "Hello, World!";
int length = strlen(str);
printf("Length of the string: %d\n", length);

strlen函数返回字符串的长度,不包括'\0'

2. 手动计算长度

char str[] = "Hello, World!";
int length = 0;
while (str[length] != '\0') {
    length++;
}
printf("Length of the string: %d\n", length);

通过遍历字符数组直到遇到'\0',可以手动计算字符串的长度。

字符串的复制

1. 使用strcpy函数

#include <string.h>

char src[] = "Hello, World!";
char dest[50];
strcpy(dest, src);
printf("Copied string: %s\n", dest);

strcpy函数将src字符串复制到dest中,包括'\0'

2. 使用strncpy函数

#include <string.h>

char src[] = "Hello, World!";
char dest[50];
strncpy(dest, src, 5);
dest[5] = '\0';
printf("Copied string: %s\n", dest);

strncpy函数将src字符串的前n个字符复制到dest中,不会自动添加'\0',因此需要手动添加。

3. 手动复制

char src[] = "Hello, World!";
char dest[50];
int i = 0;
while (src[i] != '\0') {
    dest[i] = src[i];
    i++;
}
dest[i] = '\0';
printf("Copied string: %s\n", dest);

通过遍历src字符串并逐个字符复制到dest中,可以手动实现字符串复制。

字符串的连接

1. 使用strcat函数

#include <string.h>

char str1[50] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);

strcat函数将str2字符串连接到str1的末尾,包括'\0'

2. 使用strncat函数

#include <string.h>

char str1[50] = "Hello, ";
char str2[] = "World!";
strncat(str1, str2, 3);
printf("Concatenated string: %s\n", str1);

strncat函数将str2字符串的前n个字符连接到str1的末尾,并自动添加'\0'

3. 手动连接

char str1[50] = "Hello, ";
char str2[] = "World!";
int i = 0, j = 0;
while (str1[i] != '\0') {
    i++;
}
while (str2[j] != '\0') {
    str1[i] = str2[j];
    i++;
    j++;
}
str1[i] = '\0';
printf("Concatenated string: %s\n", str1);

通过遍历str1找到末尾,然后将str2的字符逐个复制到str1的末尾,可以手动实现字符串连接。

字符串的比较

1. 使用strcmp函数

#include <string.h>

char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2);
if (result == 0) {
    printf("Strings are equal\n");
} else if (result < 0) {
    printf("str1 is less than str2\n");
} else {
    printf("str1 is greater than str2\n");
}

strcmp函数比较两个字符串,返回值为0表示相等,小于0表示str1小于str2,大于0表示str1大于str2

2. 使用strncmp函数

#include <string.h>

char str1[] = "Hello";
char str2[] = "World";
int result = strncmp(str1, str2, 3);
if (result == 0) {
    printf("First 3 characters are equal\n");
} else if (result < 0) {
    printf("First 3 characters of str1 are less than str2\n");
} else {
    printf("First 3 characters of str1 are greater than str2\n");
}

strncmp函数比较两个字符串的前n个字符,返回值与strcmp相同。

3. 手动比较

char str1[] = "Hello";
char str2[] = "World";
int i = 0;
while (str1[i] != '\0' && str2[i] != '\0') {
    if (str1[i] != str2[i]) {
        break;
    }
    i++;
}
if (str1[i] == '\0' && str2[i] == '\0') {
    printf("Strings are equal\n");
} else if (str1[i] < str2[i]) {
    printf("str1 is less than str2\n");
} else {
    printf("str1 is greater than str2\n");
}

通过逐个字符比较两个字符串,可以手动实现字符串比较。

字符串的查找

1. 使用strchr函数

#include <string.h>

char str[] = "Hello, World!";
char *result = strchr(str, 'o');
if (result != NULL) {
    printf("Found 'o' at position: %ld\n", result - str);
} else {
    printf("'o' not found\n");
}

strchr函数在字符串中查找指定字符的第一个出现位置,返回指向该位置的指针,如果未找到则返回NULL

2. 使用strrchr函数

#include <string.h>

char str[] = "Hello, World!";
char *result = strrchr(str, 'o');
if (result != NULL) {
    printf("Found last 'o' at position: %ld\n", result - str);
} else {
    printf("'o' not found\n");
}

strrchr函数在字符串中查找指定字符的最后一个出现位置,返回指向该位置的指针,如果未找到则返回NULL

3. 使用strstr函数

#include <string.h>

char str[] = "Hello, World!";
char *result = strstr(str, "World");
if (result != NULL) {
    printf("Found 'World' at position: %ld\n", result - str);
} else {
    printf("'World' not found\n");
}

strstr函数在字符串中查找指定子字符串的第一个出现位置,返回指向该位置的指针,如果未找到则返回NULL

4. 手动查找

char str[] = "Hello, World!";
char target = 'o';
int i = 0;
while (str[i] != '\0') {
    if (str[i] == target) {
        printf("Found '%c' at position: %d\n", target, i);
        break;
    }
    i++;
}
if (str[i] == '\0') {
    printf("'%c' not found\n", target);
}

通过遍历字符串并逐个字符比较,可以手动实现字符查找。

字符串的截取

1. 使用strncpy函数

#include <string.h>

char str[] = "Hello, World!";
char substr[10];
strncpy(substr, str + 7, 5);
substr[5] = '\0';
printf("Substring: %s\n", substr);

strncpy函数可以从指定位置开始截取指定长度的子字符串。

2. 手动截取

char str[] = "Hello, World!";
char substr[10];
int start = 7, length = 5;
int i = 0;
while (i < length) {
    substr[i] = str[start + i];
    i++;
}
substr[i] = '\0';
printf("Substring: %s\n", substr);

通过从指定位置开始复制指定长度的字符,可以手动实现字符串截取。

字符串的替换

1. 使用strstrstrncpy函数

#include <string.h>

char str[] = "Hello, World!";
char old[] = "World";
char new[] = "C";
char result[50];
char *pos = strstr(str, old);
if (pos != NULL) {
    strncpy(result, str, pos - str);
    result[pos - str] = '\0';
    strcat(result, new);
    strcat(result, pos + strlen(old));
    printf("Result: %s\n", result);
} else {
    printf("Substring not found\n");
}

通过查找子字符串的位置,然后使用strncpystrcat函数进行替换。

2. 手动替换

char str[] = "Hello, World!";
char old[] = "World";
char new[] = "C";
char result[50];
int i = 0, j = 0;
while (str[i] != '\0') {
    if (strstr(&str[i], old) == &str[i]) {
        strcpy(&result[j], new);
        i += strlen(old);
        j += strlen(new);
    } else {
        result[j] = str[i];
        i++;
        j++;
    }
}
result[j] = '\0';
printf("Result: %s\n", result);

通过遍历字符串并逐个字符比较,可以手动实现字符串替换。

字符串的转换

1. 使用touppertolower函数

#include <ctype.h>

char str[] = "Hello, World!";
int i = 0;
while (str[i] != '\0') {
    str[i] = toupper(str[i]);
    i++;
}
printf("Uppercase string: %s\n", str);

i = 0;
while (str[i] != '\0') {
    str[i] = tolower(str[i]);
    i++;
}
printf("Lowercase string: %s\n", str);

toupper函数将字符转换为大写,tolower函数将字符转换为小写。

2. 手动转换

char str[] = "Hello, World!";
int i = 0;
while (str[i] != '\0') {
    if (str[i] >= 'a' && str[i] <= 'z') {
        str[i] = str[i] - 32;
    }
    i++;
}
printf("Uppercase string: %s\n", str);

i = 0;
while (str[i] != '\0') {
    if (str[i] >= 'A' && str[i] <= 'Z') {
        str[i] = str[i] + 32;
    }
    i++;
}
printf("Lowercase string: %s\n", str);

通过判断字符的ASCII值并进行加减操作,可以手动实现字符串的大小写转换。

字符串的分割

1. 使用strtok函数

#include <string.h>

char str[] = "Hello, World!";
char *token = strtok(str, " ,!");
while (token != NULL) {
    printf("Token: %s\n", token);
    token = strtok(NULL, " ,!");
}

strtok函数根据指定的分隔符将字符串分割成多个子字符串,每次调用返回一个子字符串。

2. 手动分割

char str[] = "Hello, World!";
char delimiter = ' ';
char *start = str;
char *end = str;
while (*end != '\0') {
    if (*end == delimiter) {
        *end = '\0';
        printf("Token: %s\n", start);
        start = end + 1;
    }
    end++;
}
printf("Token: %s\n", start);

通过遍历字符串并根据分隔符进行分割,可以手动实现字符串分割。

字符串的格式化

1. 使用sprintf函数

#include <stdio.h>

char str[50];
int num = 123;
sprintf(str, "The number is %d", num);
printf("Formatted string: %s\n", str);

sprintf函数将格式化的数据写入字符串中。

2. 使用snprintf函数

#include <stdio.h>

char str[50];
int num = 123;
snprintf(str, sizeof(str), "The number is %d", num);
printf("Formatted string: %s\n", str);

snprintf函数将格式化的数据写入字符串中,并限制写入的字符数量。

3. 手动格式化

char str[50];
int num = 123;
int i = 0;
char *format = "The number is %d";
while (format[i] != '\0') {
    str[i] = format[i];
    i++;
}
sprintf(&str[i], "%d", num);
printf("Formatted string: %s\n", str);

通过手动拼接字符串和格式化数据,可以手动实现字符串格式化。

字符串的其他操作

1. 使用memcpy函数

#include <string.h>

char src[] = "Hello, World!";
char dest[50];
memcpy(dest, src, strlen(src) + 1);
printf("Copied string: %s\n", dest);

memcpy函数将指定数量的字节从源内存区域复制到目标内存区域。

2. 使用memset函数

#include <string.h>

char str[50];
memset(str, 'A', 49);
str[49] = '\0';
printf("Filled string: %s\n", str);

memset函数将指定数量的字节设置为指定值。

3. 使用memcmp函数

#include <string.h>

char str1[] = "Hello";
char str2[] = "World";
int result = memcmp(str1, str2, 5);
if (result == 0) {
    printf("First 5 bytes are equal\n");
} else if (result < 0) {
    printf("First 5 bytes of str1 are less than str2\n");
} else {
    printf("First 5 bytes of str1 are greater than str2\n");
}

memcmp函数比较两个内存区域的前n个字节,返回值与strcmp相同。

4. 使用memmove函数

#include <string.h>

char str[] = "Hello, World!";
memmove(str + 7, str, 5);
printf("Moved string: %s\n", str);

memmove函数将指定数量的字节从源内存区域移动到目标内存区域,即使源

推荐阅读:
  1. C语言位操作方法有哪些
  2. Python字符串有哪些操作方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c语言

上一篇:vuex中数据持久化插件vuex-persistedstate怎么用

下一篇:如何编写第一个Go程序

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》