数组中字符串的长度
C++ Length of a string in an Array
我如何能够找到我的字符串数组的最长长度?
我有几个选项可供选择,最长的是"如何玩",有12个字符长。
简而言之,我怎样才能找到数组中最长的部分并得到它的数字呢?这是我的数组:
string mainMenuText[] = {" Play game ",
" Highscores ",
" Storyline ",
" How To Play",
" Exit Game "};
您还可以使用#include <algorithm>
:
std::string mainMenuText[] = {" Play game ", " Highscores ", " Storyline ",
" How To Play", " Exit Game "};
auto it = std::max_element(std::begin(mainMenuText), std::end(mainMenuText),
[](std::string& lhs, std::string& rhs){return lhs.size() < rhs.size();});
auto num = it->size(); // here is your max size
std::cout << "Longest: [" << *it << "] of size: " << num;
要获得string
的长度,可以使用size()
成员函数。
要找到最大的size()
,您只需要遍历所有字符串:
std::string::size_type max_size = 0;
const size_t NUM = sizeof(mainMenuText) / sizeof(*mainMenuText);
for (size_t i = 0; i < NUM; ++i) {
max_size = std::max(max_size, mainMenuText[i].size());
}
// max_size is now the maximum size
在c++ 11中,我们可以把它缩短一点:
std::string::size_type max_size = 0;
for (const std::string& s : mainMenuText) {
max_size = std::max(max_size, s.size());
}
但是,请注意,所有字符串的长度都是相同的。我不确定那是不是故意的。如果您想考虑填充,我会添加这个函数:
size_t trimmed_length(const std::string& s) {
size_t start = s.find_first_not_of(' ');
size_t end = s.find_last_not_of(' ');
return (start == std::string::npos || end == std::string::npos)
? 0 : end - start + 1;
}
:
size_t max_size = 0;
for (const std::string& s : mainMenuText) {
max_size = std::max(max_size, trimmed_length(s));
}
有一个标准算法std::max_element
,根据您的标准找到给定序列中的第一个最大元素。例如
#include <iostream>
#include <algorithm>
#include <string>
#include <iterator>
int main()
{
std::string mainMenuText[] =
{
" Play game ",
" Highscores ",
" Storyline ",
" How To Play",
" Exit Game "
};
auto *it = std::max_element( std::begin( mainMenuText ), std::end( mainMenuText ),
[]( const std::string &s1, const std::string &s2 )
{
return s1.size() < s2.size();
} );
std::cout << "The longest string is "" << *it << """ << std::endl;
std::cout << "It has " << it->size() << " characters" << std::endl;
return 0;
}
程序输出为
The longest string is " Play game "
It has 12 characters
要获取最长字符串的索引,可以使用标头<iterator>
std::distance
。例如size_t pos = std::distance( std::begin( mainMenuText ), it );
或者直接写
size_t pos = it - mainMenuText;
简单代码
int max=0;
for(int i=0;i<5;i++)
if(mainMenuText[i].size()>mainMenuText[max].size())
max=i;
return mainMenuText[max];
您忘记包含字符串库了。
#include <string>
using namespace std;
把它放在你的代码文件上面
相关文章:
- 将C#字符串数组传递给C++
- 如何为 C 型字符串数组编写 getter 和 setter?
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 尝试将 c 字符串数组与分隔符连接起来
- 将字符串数组传递给接受常量字符**的函数
- 返回 C++ 中的字符串数组
- 如何从COM模块中的函数返回字符串数组?
- 无法将字符串数组声明为类成员而不是字符 (C++)
- 删除字符串数组
- 如何将字符串数组返回到 java JNI
- 将字符串数组作为函数参数传递
- C++将字符串数组的元素存储到变量中
- 循环访问还包含未使用元素的字符串数组
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 乘以字符串/数组和全局数组
- 递归二进制搜索与字符串数组
- 如何初始化一个标准::字符串数组?
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- C++字符串数组的动态向量
- 给定一个等长字符串数组