繁体   English   中英

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

[英]How to get only first words from several C++ strings?

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

谢谢我前进!

这是一种实现方法...

// 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 ++有点生锈。 干杯。

我假设这是家庭作业,所以这里是一个一般性的描述:

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

现在,您需要为该数组中的插入点创建一个索引。 从零开始。

现在按顺序遍历您的琴弦。 在每一个中,将索引从0向前移动,直到看到\\ 0或一个空格(或其他定界符)。在结果数组的插入点插入字符,然后将该索引增加1。

如果遇到空格或\\ 0,则会找到第一个单词。 如果您在最后一个字符串上,请在插入点插入\\ 0,然后完成。 如果不是,请插入空格并移至下一个字符串。

您正在使用什么编译器? 转换为chararray是要寻找的第一件事。

完成之后,您可以轻松地遍历数组(并寻找空格),如下所示:

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

我认为您必须自己解决其余的问题,因为这看起来像是学校的家庭作业:)

假设这是家庭作业,那么当您说“字符串”时,您的意思是简单的以空char分隔的char数组(而不是std::string ):

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

如果这不是家庭作业,请给我们一些代码以开始,我们将填补空白。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM