如何从字符串中提取单词并将它们存储在c ++中的不同数组中

0 c++ string split

如何string在不使用strtokistringstream找到最大的单词的情况下将单词拆分并存储在单独的数组中?我只是一个初学者,所以我应该做到这一点使用基本功能string.h中一样strlen,strcpy只有等.有可能吗?我试图这样做,我发布了我所做的.请纠正我的错误.

#include<iostream.h>
#include<stdio.h>
#include<string.h>
void count(char n[])
{
    char a[50], b[50];
    for(int i=0; n[i]!= '\0'; i++)
    {
        static int j=0;
        for(j=0;n[j]!=' ';j++)
        {
            a[j]=n[j];
        }
        static int x=0;
        if(strlen(a)>x)
        {
            strcpy(b,a);
            x=strlen(a);
        }
    }
    cout<<"Greatest word is:"<<b;
}

int main( int, char** )
{
    char n[100];
    gets(n);
    count(n);
}
Run Code Online (Sandbox Code Playgroud)

Snp*_*nps 5

您的示例中的代码看起来像是用C语言编写的.函数strlenstrcpyC 一样起源(尽管它们也是C++标准库的一部分,用于通过标题进行兼容cstring).

您应该使用标准库开始学习C++ ,事情会变得更加容易.如果您使用标准库中的函数,则可以使用几行代码来分割字符串和查找最大元素,例如:

// The text
std::string text = "foo bar foobar";

// Wrap text in stream.
std::istringstream iss{text};
// Read tokens from stream into vector (split at whitespace).
std::vector<std::string> words{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};
// Get the greatest word.
auto greatestWord = *std::max_element(std::begin(words), std::end(words), [] (const std::string& lhs, const std::string& rhs) { return lhs.size() < rhs.size(); });
Run Code Online (Sandbox Code Playgroud)

编辑: 如果你真的想只使用函数来挖掘细节std::string,那么你可以将文本分成单词(我留下找到最好的单词给你,这不应该太难):

// Use vector to store words.
std::vector<std::string> words;
std::string text = "foo bar foobar";

std::string::size_type beg = 0, end;
do {
    end = text.find(' ', beg);
    if (end == std::string::npos) {
        end = text.size();
    }
    words.emplace_back(text.substr(beg, end - beg));
    beg = end + 1;
} while (beg < text.size());
Run Code Online (Sandbox Code Playgroud)