删除字符串的字符

我正在尝试编写一个代码,要求用户输入一个字符串并除了按字母顺序排列所有字符。

现在我自己做了,似乎没有正常工作。 我是字符串的新手,所以我正在努力理解和掌握字符串。 我试图在Mac上使用gdb,但我没有所有的function来理解这一点。 能否请你帮忙?

代码必须做什么:用户输入(例如): h**#el(l)o&^w

输出是hello.

这是我的代码:

 #include  #include  int main() { char string[100]; int i; int seen = 0; printf("Enter String: "); scanf("%s", string); for (i=0; string[i]!='\0'; i++) { if (((string[i]'z')&&(string[i]'Z')) ||string[i]!='\0') { seen = 1; } else seen = 0; } if (seen==0) { printf("%s", string); } } 

好吧,你的代码有几个重要的问题:

  • 你在迭代时没有检查边界……如果我输入一个101个字符的字符串怎么办? 和4242个字符串?
  • 下一个问题是, scanf("%s", …) 被认为是危险的,原因相同

所以基本上,你想要的是使用fgets()而不是scanf()

但是为什么不只是按字符获取输入字符,并构建一个只有你想要的字符的字符串? 它更简单灵活!

基本上:

 #include  int main() { char* string[100]; int i=0; printf("Enter your string: "); do { // getting a character char c = getchar(); // if the character is alpha if (isalpha(c) != 0) // we place the character to the current position and then increment the index string[i++] = c; // otherwise if c is a carriage return else if (c == '\r') { c = getchar(); // get rid of \n // we end the string string[i] = '\0' }else if (c == '\n') // we end the string string[i] = '\0'; // while c is not a carriage return or i is not out of boundaries } while (c != '\n' || i < 100); // if we've got to the boundary, replace last character with end of string if (i == 100) string[i] = '\0'; // print out! printf("Here's your stripped string: %s\n", string); return 0; } 

我没有在我的电脑上运行它,因为它已经迟到了,所以我在出错的时候道歉。

附录:

程序会跳过我的陈述并关闭

这是因为你的条件是反转的,并删除\0条件,因为它总是会发生在scanf()总是将\0附加到字符串以结束它。 尝试交换seen = 1seen = 0或尝试使用以下条件:

  if ((string[i]>='a' && string[i]<='z')||(string[i]>='A' && string[i]<='Z'))) seen = 1; else seen = 0; 

或者简单地说,使用ctypesisalpha()函数,就像在我们的两个例子中一样!

没有任何部分(删除多余的字符)来更改代码中的字符串。

 #include  #include  #include  char *filter(char *string, int (*test)(int)) { char *from, *to; for(to = from = string;*from;++from){ if(test(*from)) *to++ = *from; } *to = '\0'; return string; } int main(){ char string[100]; printf("Enter String: "); scanf("%99s", string); printf("%s\n", filter(string, isalpha)); return 0; }