gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 16:18:33 25 4
gpt4 key购买 nike

如何在不使用 strtokistringstream 的情况下拆分 string 并将单词存储在单独的数组中并找到最大的单词?我只是一个初学者,所以我应该只使用 string.h 中的基本函数来完成此操作,例如 strlenstrcpy 等。这样做可以吗??我已经尝试这样做,并且正在发布我所做的事情。请纠正我的错误。

#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);
}

最佳答案

您示例中的代码看起来像是用 C 语言编写的。strlenstrcpy 等函数源自 C(尽管它们也是 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(); });

编辑:如果您真的想仅使用 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());

关于c++ - 如何从字符串中提取单词并将它们存储在 C++ 中的不同数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19812381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com