C语言如何去除字符串中的空格
在C语言中,我们可以使用一些算法来去除字符串中的空格,本文将介绍两种常见的方法:一种是使用循环遍历字符串,逐个字符判断是否为空格;另一种是使用字符串处理函数strtok
,下面我们将详细介绍这两种方法。
1、创建一个字符数组,用于存储去除空格后的字符串。
2、使用循环遍历输入的字符串,逐个字符判断是否为空格。
3、如果当前字符不是空格,则将其添加到新的字符串中。
4、循环结束后,新的字符串即为去除空格后的字符串。
代码示例:
include <stdio.h> include <string.h> void remove_spaces(char *input, char *output) { int i = 0, j = 0; while (input[i]) { if (input[i] != ' ') { output[j++] = input[i]; } i++; } output[j] = '0'; } int main() { char input[] = "Hello World!"; char output[strlen(input) + 1]; remove_spaces(input, output); printf("去除空格后的字符串: %s ", output); return 0; }
strtok
函数1、需要包含头文件<string.h>
。
2、定义一个字符数组,用于存储去除空格后的字符串,注意,我们需要预先分配足够的内存空间,以防止溢出。
3、调用strtok
函数,传入原始字符串和分隔符(在这里是空格)。strtok
函数会返回下一个分割后的子串的指针,如果没有更多的子串,返回NULL。
4、在循环中调用strtok
函数,直到返回NULL为止,每次调用都会更新当前子串的指针。
5、将当前子串复制到新的字符串中。
6、新的字符串即为去除空格后的字符串,需要注意的是,由于strtok
函数会修改原始字符串,所以在使用它之前需要先复制一份原始字符串。
代码示例:
include <stdio.h> include <string.h> include <stdlib.h> char *remove_spaces(const char *input) { char *token = strtok(const_cast<char *>(input), " "); static char output[1024]; // 需要预先分配足够的内存空间 memset(output, 0, sizeof(output)); // 防止溢出 while (token != NULL) { strcat(output, token); // 将当前子串复制到新的字符串中 strcat(output, " "); // 在新的字符串中添加分隔符(这里是空格)和空字符('