How to remove spaces from a string in the C language?

There are two methods to remove spaces from a string.

Option 1: Use a loop to iterate through the string, copying non-space characters to a new string.

#include <stdio.h>
#include <string.h>

void removeSpaces(char *str) {
    int i, j;
    for (i = 0, j = 0; str[i]; i++) {
        if (str[i] != ' ') {
            str[j++] = str[i];
        }
    }
    str[j] = '\0'; // 在新字符串的末尾添加结束符
}

int main() {
    char str[100];
    printf("输入字符串:");
    gets(str);
    removeSpaces(str);
    printf("删除空格后的字符串:%s\n", str);
    return 0;
}

Option two: Delete spaces directly from the original string using pointer manipulation.

#include <stdio.h>
#include <string.h>

void removeSpaces(char *str) {
    char *p = str;
    while (*str) {
        if (*str != ' ') {
            *p++ = *str;
        }
        str++;
    }
    *p = '\0'; // 在新字符串的末尾添加结束符
}

int main() {
    char str[100];
    printf("输入字符串:");
    gets(str);
    removeSpaces(str);
    printf("删除空格后的字符串:%s\n", str);
    return 0;
}

The choice between the two methods for removing spaces from a string depends on personal preference and specific needs.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds