在C中删除字符串中的点
我正在C中制作一个小程序,我会在其中放入几个数字和点,然后删除所有点(。)。
我正在考虑一个循环,但我似乎不太明白我接下来应该做什么。 到目前为止我得到了这个:
#include #include #include int main(int argc, char *argv[]) { char s[30]; int k=0; printf("Enter your account number including dots. \n"); gets(s); printf("Account number without dots:"); while (s[k]!=0) { //????? } return 0;
我是在正确的轨道上还是应该以不同的方式开始并且根本不使用while循环? 我只能找到一个解决方案,其中有一个特定的字符串不是由用户编写的,而是由程序员编写的……
放入IF只打印不是点的字符。 与其他人建议的一样,您也应该将获取更改为fgets。
#include #include #include int main(int argc, char *argv[]) { char s[30]; int k=0; printf("Enter your account number including dots. \n"); gets(s); printf("Account number without dots:"); while (s[k]!=0) { if ( s[k] != '.' ) { printf("%c", s[k]); } k++; } printf("\n"); return 0; }
使用while循环,我还担心如果用户输入完整的30个字符,您将无法达到退出条件。 为了避免这个问题,for循环会更好(因为你已经知道了数组的大小)。 但是,如果你这样做,你还需要将数组“s”初始化为空白。
#include #include #include int main(int argc, char *argv[]) { char s[30]; int k=0; printf("Enter your account number including dots. \n"); gets(s); printf("Account number without dots:"); for ( k = 0 ; k < 30 ; k++ ) { if ( s[k] != '.' && s[k] != 0 ) { printf("%c", s[k]); } k++; } printf("\n"); return 0; }
#include #include #include int main(int argc, char *argv[]) { char s[30]; int k=0; printf("Enter your account number including dots. \n"); gets(s); printf("Account number without dots:"); while (s[k]!=0) { if(s[k] == '.') s[k] = s[k + 1]; k++; } s[k] = '\0'; return 0;
#include //remove the specified character from str char *strrmc(char *str, char ch){ char *from, *to; from = to = str; while(*from){ if(*from == ch) ++from; else *to++ = *from++; } *to = '\0'; return str; } int main(int argc, char *argv[]){ char s[30] = "192.169.007"; printf("%s\n", strrmc(s, '.'));//192169007 return 0; }
这是您可以采用的一种方式 – 它与您的开始方式不同,但可以轻松修改。 它也可以改进,但我们可以在进一步的评论中对此进行狡辩。 🙂
#include #include #include int main(int argc, char *argv[]) { /* Take account number in as argument to executable */ int dotless_length = 30; char dotless[dotless_length]; int k = 0; int i = 0; while (argv[1][k] != '\0' && i < dotless_length) { if (argv[1][k] >= 48 && argv[1][k] <= 57) { /* ascii decimal codes for 0-9 */ dotless[i] = argv[1][k]; i++; } else if (argv[1][k] != '.') { printf("invalid input: %c\n", argv[1][k]); return 1; } k++; } dotless[i] = '\0'; /* null-terminate it! */ printf("Account number without dots: %s\n", dotless); return 0; }
然后用gcc -Wall -o zdotless filename.c
编译并运行
./zdotless 401.863.3000
作为例子。
注意 :这可能看起来更难,因为它比原来更多地进入输入卫生(和清洁度) - 例如
- 不假设用户输入仅包含数字和句点,
- 保存得到的无点字符串(对于可能的未来操作?),
- 有一个地方可以改变无点的长度(朝着不硬编码的方向迈进),以及
- 没有互动。
当您调用可执行文件时, argv
就是您输入的内容,因此argv[0]
是可执行文件名( ./zdotless
argv[1]
是下一个参数( 401.863.3000
作为字符串),依此类推有更多的论点。 由于argv[1]
是你的dotty输入数字的字符串表示, argv[1][0]
是它的第一个字符,等等。
由于我们要dotless
字符地复制到dotless
点字符而不是使用字符串操作,因此您必须手动处理空字符。 (同样的空字符是你在最初读取输入字符串时到达的循环。)其他问题?...