[英]Removing a character from string in C with a dynamic string
因此,我想創建一個函數,該函數基於不帶字符c的字符串s 創建並返回動態字符串。 現在,無論哪種情況,我都希望能夠刪除所有所需的字符。 此外,用戶輸入的原始字符串應保持不變。 這是我的嘗試,它總是在第12行告訴我有關錯誤的信息(注釋中已指出)。
還有一件事:我不確定我是否很好地編寫了remove函數,我認為它應該可以工作嗎? 所有的指針使我有些困惑。
#include <stdio.h>
#include <stdlib.h>
char * remove(char *s, char c);
int strlen(char *s);
int main() {
char s[16], c, n[16];
printf("Please enter string: ");
scanf("%s", s);
printf("Which character do you want to remove? ");
scanf("%c", &c);
n = remove(s, c); // Place the new string in n so I wouldn't change s (the error)
printf("The new string is %s", n);
return 0;
}
int strlen(char *s)
{
int d;
for (d = 0; s[d]; d++);
return d;
}
char * remove(char *s, char c) {
char str[16], c1;
int i;
int d = strlen(s);
str = (char)calloc(d*sizeof(char)+1);
// copying s into str so I wouldn't change s, the function returns str
for (i = 0; i < d; i++) {
while(*s++ = str++);
}
// if a char in the user's string is different than c, place it into str
for (i = 0; i < d; i++) {
if (*(s+i) != c) {
c1 = *(s+i);
str[i] = c1;
}
}
return str; // the function returns a new string str without the char c
}
您將n
聲明為char類型的16元素數組:
char n[16];
因此,您無法執行以下操作:
n = remove(s, c);
因為n
是const指針。
同樣,您的remove
函數將返回一個指向其本地數組的指針,該指針將在函數返回后立即銷毀。 更好的聲明remove
為
void remove(char *to, char *from, char var);
並傳遞n
作為第一個參數。
在您的程序中發現了如此多的錯誤,因此添加注釋后,更容易重寫和顯示。 請注意, scanf("%s...
將只接受一個單詞,而不是一個句子(它停在第一個空白處)。並且請注意, newline
將留在scanf("%c...
的輸入緩沖區中除非另有說明,否則請閱讀。
#include <stdio.h>
void c_remove(char *n, char *s, char c) { // renamed because remove() is predefined
while (*s) { // no need for strlen()
if (*s != c) // test if char is to be removed
*n++ = *s; // copy if not
s++; // advance source pointer
}
*n = '\0'; // terminate new string
}
int main(void) { // correct signature
char s[16], c, n[16];
printf("Please enter string: ");
scanf("%s", s);
printf("Which character do you want to remove? ");
scanf(" %c", &c); // the space before %c cleans off whitespace
c_remove(n, s, c); // pass target string pointer too
printf("The new string is %s", n);
return 0;
}
計划會議:
Please enter string: onetwothree
Which character do you want to remove? e
The new string is ontwothr
Please enter string: onetwothree
Which character do you want to remove? o
The new string is netwthree
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.