删除C中的字符串中的点 [英] Removing dots in a string in C

查看:161
本文介绍了删除C中的字符串中的点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C中制作了一个小程序,我将放入一些数字和点,然后删除所有的点(。)。

I'm making a little program in C where I would put in a couple of numbers and dots and then delete all the dots (.).

思考一个whileloop,但我似乎不太明白我应该做什么下一步。到目前为止,我得到了:

I was thinking about a whileloop but I cannot seem to quite understand what I should do next. So far I got this:

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

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循环吗?我只能找到解决方案,其中有一个特定的字符串,不是由用户写的,而是由程序员...

Am I on the right track or should I start differently and not use a while loop at all? I can only find solutions where there is a specific string that is not written by the user, but by the programmer...

推荐答案

放入IF以仅打印不是点的字符。像其他人建议的那样,你应该也可以把get改成fgets。

Put in an IF to only print characters that aren't a dot. Like the others suggested, you should probably change the gets to fgets as well.

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

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为空。

With a while loop, I'm also worried that if the user puts in a full 30 characters, you won't reach your exit condition. To avoid this problem, a for loop would be better (since you already know the size of the array). However, if you do it this way, you'll also need to initialize your array "s" to be blank.

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

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;
}

这篇关于删除C中的字符串中的点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆