如何只从几个C ++字符串中获取第一个单词?

时间:2010-05-26 13:53:02

标签: c++ string

我有几个带有一些单词的C ++字符串。我需要从每个字符串中获取第一个字。然后我必须将它们全部放入char数组中。我该怎么办?

谢谢我提前!

4 个答案:

答案 0 :(得分:3)

这是一种做法......

// SO2913562.cpp 
//


#include <iostream>
#include <sstream>
using namespace std;


void getHeadWords(const char *input[]
                    , unsigned numStrings 
                    , char *outBuf
                    , unsigned outBufSize)
{
    string outStr = "";

    for(unsigned i = 0; i<numStrings; i++)
    {
        stringstream ss(stringstream::in|stringstream::out);
        ss<<input[i];

        string word;
        ss>>word;
        outStr += word;

        if(i < numStrings-1)
            outStr += " ";
    }

    if(outBufSize < outStr.size() + 1)//Accomodate the null terminator.
        //strncpy omits the null terminator if outStr is of the exact same
        //length as outBufSize
        throw out_of_range("Output buffer too small");

    strncpy(outBuf, outStr.c_str(), outBufSize);
}

int main () 
{
    const char *lines[] = {
        "first sentence"
        , "second sentence"
        , "third sentence"
    };

    char outBuf[1024];

    getHeadWords(lines, _countof(lines), outBuf, sizeof(outBuf));

    cout<<outBuf<<endl;

    return 0;
}

但请注意,上面的代码有边缘错误检查,可能存在安全漏洞。不用说我的C ++有点生疏了。欢呼声。

答案 1 :(得分:2)

我会假设它是作业,所以这里是一般性描述:

首先,您需要在char数组中分配足够的空间。在作业中,通常会告诉您最大尺寸。所有第一个单词的最大值必须足够。

现在,您需要为该数组中的插入点设置索引。从零开始。

现在按顺序翻看你的字符串。在每个中,将索引从0向前移动,直到看到\ 0或空格(或其他分隔符。在结果数组中的插入点插入字符,并将该索引增加1。

如果您遇到空格或\ 0,您就找到了第一个单词。如果您在最后一个字符串上,请在插入点插入\ 0,然后就完成了。如果没有,请插入空格并移动到下一个字符串。

答案 2 :(得分:1)

你正在使用什么编译器? 转换为chararray是首先要寻找的。

完成后,您可以轻松地单步执行数组(并查找空格) 像这样的东西:

while (oldarray[i++] != ' ')
  yournewarray[j++];

我认为你必须自己弄清楚其余部分,因为这看起来像学校的一些功课:)

答案 3 :(得分:1)

假设这是家庭作业,当你说“字符串”时,你指的是char(而不是std::string)的简单的以null分隔的数组:

define your strings  
define your resulting char array  
for each string  
    find the offset of the first char that is not in the first word
    append that many bytes of the string to the result array

如果这不是作业,请先给我们一些代码,然后填写空白。

相关问题