数组中字符串的长度

C++ Length of a string in an Array

本文关键字:字符串 数组      更新时间:2023-10-16

我如何能够找到我的字符串数组的最长长度?
我有几个选项可供选择,最长的是"如何玩",有12个字符长。
简而言之,我怎样才能找到数组中最长的部分并得到它的数字呢?这是我的数组:

string mainMenuText[] = {" Play game  ",
                         " Highscores ",
                         " Storyline  ", 
                         " How To Play", 
                         " Exit Game  "};

您还可以使用#include <algorithm>:

中的现代c++标准库功能:
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; 

把它放在你的代码文件上面