string中单词统计

编程背景:已知有string对象,编写程序分离该string中所有单词,将包含'.'的单词转换为float类型,其他的单词转换为int类型

Pass1: 分离单词

    string word;
    char sep = ' ';
    
    int startPos = 0, endPos = 0, wordlen = 0;
    endPos = ss.find_first_of(sep,endPos); //第一个单词是以' '结尾,和下面的while循环处理的情况不同
    if (endPos == string::npos)
        wordlen = ss.size() - startPos;
    else
        wordlen = endPos - startPos;
    
    word.assign(ss.begin() + startPos, ss.begin() + startPos + wordlen);
    cout << word << endl;
    startPos = ss.find_first_not_of(sep, endPos); //设置下次查找的起始位置

    while((startPos=ss.find_first_of(sep, endPos)) != string::npos) //找到下一单词起始位置
    {
        ++startPos;
        endPos = ss.find_first_of(sep, startPos); //找到下一个单词的结束位置
        if ((endPos - startPos) != 0) //未连续取了用作分隔的字符
        {
            if(endPos == string::npos)
                wordlen = ss.size() - startPos;
            else
                wordlen = endPos - startPos;
            word.assign(ss.begin() + startPos, ss.begin() + startPos + wordlen); //获取单词
            cout << word << endl;
            startPos = ss.find_first_not_of(sep, endPos);
        }
        //连续取了用作分隔的字符
    }
//最后一个单词的处理,创建文件的时候注意添加一个空白符;或者在while循环结束之后特别处理

 

Pass2: string转换为int和float

char c = '.';
if ( word.find(c) != -1)
    float f = atof(word.c_str());
else
    int d = atoi(word.c_str());

 

 

 

posted on 2012-04-25 20:58  拼装小火车  阅读(416)  评论(0编辑  收藏  举报