CDOJ_327 BerOS file system

原题地址:http://acm.uestc.edu.cn/#/problem/show/327




The new operating system BerOS has a nice feature. It is possible to use any number of characters / as a delimiter in path instead of one

 traditional /. For example, strings //usr///local//nginx/sbin// and /usr/local/nginx///sbin are equivalent. The character / (or some 

sequence of such characters) at the end of the path is required only in case of the path to the root directory, which can be represented as 

single character /.

A path called normalized if it contains the smallest possible number of characters /.

Your task is to transform a given path to the normalized form.

Input

There are multi-cases. The first line of each case contains only lowercase Latin letters and character / — the path to some directory. All paths 

start with at least one character /. The length of the given line is no more than 100 characters, it is not empty.

Output

The path in normalized form.

Sample input and output

Sample Input Sample Output
//usr///local//nginx/sbin
/usr/local/nginx/sbin
题目大意是将路径化为linux下的最简格式,即目录间由一个斜杠隔开,根目录前有一个斜杠。说白了就是将多个斜杠变为一个。

此题可以使用常规思路,利用开关变量,不断判断是否为字母,然后整个单词输出。但是,巧妙利用C++的流处理,能非常简单的处理这道题。 首先
,需要声明库<sstream>,这是处理字符串流的库。然后创建一个输入流isstream is(s)(注意,这里的输入并非指从键盘敲入,而是从字符串中
输入),其中s是题中的字符串。接下来,就将is当作cin用,就可以啦。当然,需要处理一下刚开始的字符串,将所有/替换为空格。且需要注意的是
,有一种特例是全为/,这种情况只需判断一下是否输出即可。 献上代码:
#include<iostream>
#include<string>
#include<sstream>
using namespace std;

int main()
{
    string s, temp;
    while (cin >> s)
    {
        for (int i = 0; i < s.length(); i++)
            if (s[i] == '/')
                s.replace(i, 1, 1, ' ');//将斜杠代换为空格
        istringstream is(s);//创建输入流
        bool flag = 0;//判断是否有输入
        while (is >> temp)
        {
            cout << '/' << temp; 
            flag = 1;
        }
        if (!flag)
            cout << '/';
        cout << endl;
    }
    return 0;
}



posted @ 2014-04-18 19:39  好地方bug  阅读(170)  评论(0编辑  收藏  举报