簡體   English   中英

C:嘗試在不使用任何字符串庫函數的情況下從字符串中刪除空格

[英]C : trying to remove spaces from a string without using any string library functions

所以我試圖找出一種方法來打印一個沒有空格的字符串,但由於某種原因它不起作用,每當我在程序中輸入一個字符串時,它最終什么都不打印。

#include <stdio.h>

char *removeSpaces(char *inString);

int main() {
    char str1[50];
    printf("Enter a string : ");
    scanf("%s", &str1);
    removeSpaces(str1);
}

char *removeSpaces(char *inString) {
    char str2[50];
    int j = 0;

    for (int i = 0; i < 50; i++) {
        if (inString[i] != ' ') {
            str2[j] = inString[i];
            j++;
        }
    }

    for (int i = 0; i < 50; i++) {
        printf("%s", str2[i]);
    }
}

您還可以使用指針遍歷 memory 位置,測試每個 position 是否有不需要的char值,這是您的 function 修改為使用該方法:

char *removeSpaces(char *inString);// your original prototype
char *remove_char(char *inString, char c);//generalized  

int main(void) {
    //use suggestions in other answer for correct user input
    const char str1[] = {"this is a string with spaces"};//for simple illustration

    printf("%s\n", removeSpaces(str1));
    printf("%s\n", remove_char(str1, ' '));
    return 0;
}

char *removeSpaces(char *inString)// your original prototype
{
    if(!inString) return (char *)"bad input";
    char *from; // "read" pointer
    char *to; // "write" pointer

    from = to = inString; // init both read and write pointers to original string

    while (*from) 
    { 
        if( (*from != ' ') && (*from != '\t') && (*from != '\n'))
        { 
            *to++ = *from; 
        } 
        from++; 
    } 
    *to = 0; 

    return inString;// add a return statement to return the char *
}

//optionally, create your function to remove any unwanted character
char *remove_char(char *inString, char c)//generalized  
{
    char *from; // "read" pointer
    char *to; // "write" pointer

    from = to = inString; // init both read and write pointers to original string

    while (*from) 
    { 
        if (*from != c) 
        { 
            *to++ = *from; 
        } 
        from++; 
    }  
   *to = 0; 

    return inString;// add a return statement to return the char *
}

輸入方式錯誤

下面不會掃描到str1任何帶有空格的東西。

// bad
char str1[50];
scanf("%s", &str1);

相反,使用fgets()讀取一行並形成一個字符串

char str1[50];
if (fgets(str1, sizeof str, stdin)) {
  // success!

如果需要,去掉潛在的尾隨'\n'

  str1[strcspn(str1, "\n")] = '\0';

讀取字符串末尾

循環讀取數組的大小。 它應該循環到null 字符

// for (int i = 0; i < 50; i++)
for (int i = 0; inString[i]; i++)

缺少\0

str2[]中的字符串形成不完整,因為它缺少null 字符'\0'

str2[j] = '\0'; // add after the loop

警告未完全啟用

下面應該警告"%s"str2[i]不匹配。

for (int i = 0; i < 50; i++) {
    printf("%s", str2[i]);
}

相反,沒有循環。

 printf("%s", str2);

這是在這里學到的最大的教訓。 通過完全啟用警告,編譯器可以快速提供錯誤或有問題的反饋; 比 Stackoverflow 快。

缺少退貨

char *removeSpaces(char *inString)應該返回一個char * ,但是代碼缺少return something; .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM