C语言去除字符串空格和换行符的几种方法
在C语言中,可以使用以下几种方法去掉字符串中的空格和换行符:
- 使用循环遍历字符串,将空格和换行符替换为空字符:
void removeSpacesAndNewlines(char* str) {
int i = 0;
int j = 0;
while (str[i]) {
if (str[i] != ' ' && str[i] != '\n') {
str[j++] = str[i];
}
i++;
}
str[j] = '\0';
}
- 使用strtok函数分割字符串,然后将分割后的字符串拼接起来:
void removeSpacesAndNewlines(char* str) {
char* token;
char* temp = malloc(sizeof(char) * strlen(str));
char* delimiter = " \n";
int i = 0;
token = strtok(str, delimiter);
while (token != NULL) {
strcat(temp, token);
token = strtok(NULL, delimiter);
}
strcpy(str, temp);
free(temp);
}
- 使用指针遍历字符串,跳过空格和换行符:
void removeSpacesAndNewlines(char* str) {
char* temp = str;
while (*str) {
if (*str != ' ' && *str != '\n') {
*temp = *str;
temp++;
}
str++;
}
*temp = '\0';
}
以上是三种常见的方法,可以根据具体的需求选择适合的方法。
原文地址: https://www.cveoy.top/t/topic/p0YM 著作权归作者所有。请勿转载和采集!