九度 1525:子串逆序打印

总结

1. getline(cin, string)

2. getline 不能和 scanf 联合使用. 联合使用的话, 一个数会被读入多次

题目描述:

小明手中有很多字符串卡片,每个字符串中都包含有多个连续的空格,而且这些卡片在印刷的过程中将字符串的每个子串都打印反了,现在麻烦你帮小明将这些字符串中的子串修正过来,同时为了使卡片美观,压缩其中的连续空格为1个。

思路

1. 题目本身并没有什么难度, 主要是看懂题. 题目要求的是压缩空格, 不是删除空格. WA 了很多次

代码

#include <iostream>
#include <stdio.h>
#include <string>
#include <cstdlib>
#include <cstring>
using namespace std;

char arr[10000];
string str;

void myRerverse(int len) {
    int i = 0, j = len-1;
    while(i < j) {
        swap(arr[i], arr[j]);
        i++;
        j--;
    }
}

int main() {
    
    int n;
    string str_n;
    while(getline(cin, str_n)) {
        n = atoi(str_n.c_str());
        if(n == 0) break;
        getline(cin, str);
        
        int i = 0;
        int len;

        while(i < n) {
            len = 0;
            while(i < n && str[i] == ' ') {
                i++;
                len ++;
            }
            if(len != 0)
                cout << " ";

            len = 0;
            while(i < n && str[i] != ' ') {
                arr[len] = str[i];
                i++;
                len++;
            }
            if(len != 0) {
                myRerverse(len);
                arr[len] = '';
                printf("%s", arr);
                
            }

        }
        cout << endl;
    }    
    return 0;
}
原文地址:https://www.cnblogs.com/xinsheng/p/3581064.html