牛客练习赛67 A 牛牛爱字符串

题目链接:https://ac.nowcoder.com/acm/contest/6885/A

从字符串中提取数字,并去除先导0,需要注意这里不能用while(cin>>str),因为会跳过输入字符串中的空格。

单独被分隔一个0,也需要输出,连续多个0的组合则输出最后一个0。

#include<iostream>
#include<cstring>
using namespace std;
int main(){
    string str;
    int flag;
    while(getline(cin,str)){
        flag = 0;
        for(size_t i = 0; i < str.size(); i++){
            // 为数字
            if(str[i] >= '0' && str[i] <= '9'){
                // 为0,且不为最后一位,前面也没有非0数字
                if(str[i] == '0' && flag !=2 && i != str.size() - 1 ){
                    // 先导0
                    flag = 1;
                }else{
                    // 数字
                    flag = 2;
                    cout<<str[i];
                }
            }else{
                // 全0
                if(flag == 1)cout<<0;
                // 数字后的第一个字符,输出空格
                if(flag != 0)cout<<" ";
                // 恢复状态
                flag = 0;
            }
        }
        // 换行
        cout<<endl;
    }
}