簡體   English   中英

如何從字符串中刪除所有出現的特定字符?

[英]How do I remove all occurrences of a specific char from a string?

您好我試圖從C字符串中刪除一個字符,但輸出似乎不正確。 例如,如果。 輸入字符串=“Hello”要刪除的指定字符=“l”我的輸出是“HeXXo”。 我似乎需要在刪除char之后推送值?

代碼如下:

#include <stdio.h>
#include <stdlib.h>

void squeeze(char str[], char c);

void main (){
  char input[100];
  char c;
  printf("Enter string \n");
  gets(input);
  printf("Enter char \n");
  scanf("%c", &c);
  printf("char is %c \n", c);
  squeeze(input , c );

  getchar();
  getchar();
  getchar();
}

void squeeze(char str[], char c){
    int count = 0, i = 0;   

    while (str[count] != '\0'){
      count++;
    }

    printf("Count = %d  \n", count);
    for ( i = 0 ; i != count; i++){
      if (str[i] == c){
            printf("Found at str[%d] \n", i);
            str[i] = "";
      }
    }
    printf(" String is = %s", str);
}
 str[i] = ""; 

您正在嘗試分配指針而不是字符。 你可能意味着' '但這不是從字符串中刪除字符的正確方法,而是取代它們。 嘗試:

char *p = str;
for (i = 0 ; i != count; i++) {
    if (str[i] != c)
        *p++ = str[i];
}
*p = 0;

編輯

這是我更喜歡的解決方案:

char *p = s; /* p points to the most current "accepted" char. */
while (*s) {
    /* If we accept a char we store it and we advance p. */
    if (*s != ch)
        *p++ = *s;

    /* We always advance s. */
    s++;
}
/* We 0-terminate p. */
*p = 0;
#include <stdio.h>
#include <stdlib.h>

void squeeze(char str[], char c);

int main ()
{
    char input[100];
    char c;
    printf("Enter string \n");
    gets(input);
    printf("Enter char \n");
    scanf("%c", &c);
    printf("char is %c \n", c);
    squeeze(input , c );

    return 0;
}

void squeeze(char str[], char c){
    int count = 0, i = 0,j=0;
    char str2[100];
    while (str[count] != '\0'){
        count++;}

    printf("Count = %d  \n", count);
    for ( i = 0,j=0 ; i != count; i++){
        if (str[i] == c)
        {
            printf("Found at str[%d] \n", i);
            //    str[i] = '';
        }
        else
        {
            str2[j]=str[i];
            j++ ;
        }
    }

    str2[j]='\0' ;
    printf(" String is = %s", str2);
}

這是您的代碼的修改版本。 我創建了一個新數組,並將其余的非匹配字母放入其中。 希望能幫助到你 。

str[i] = "";

您將字符串文字的地址分配給位置ichar 首先,你應該得到編譯器的警告,因為類型並不真正兼容; 其次,你需要在那里分配替換字符,例如

str[i] = '_';

或者實際上通過將所有后來的字符移回來移除它們(從而覆蓋要替換的字符)。

暫無
暫無

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

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