如何获取std::string中字符的数量?

132

我应该如何在C++中获取字符串的字符数量?


1
你正在处理什么类型的字符串?std::string?cstring?以空字符结尾的字符串? - Steve Rowe
最保险的方法是通过for循环遍历它并自己计算字符数。 - Krythic
12个回答

-1

获取字符串长度最简单的方法,而不必担心std命名空间问题,如下所示

包含/不包含空格的字符串

#include <iostream>
#include <string>
using namespace std;
int main(){
    string str;
    getline(cin,str);
    cout<<"Length of given string is"<<str.length();
    return 0;
}

没有空格的字符串

#include <iostream>
#include <string>
using namespace std;
int main(){
    string str;
    cin>>str;
    cout<<"Length of given string is"<<str.length();
    return 0;
}

-1

这可能是输入字符串并找到其长度的最简单方法。

// Finding length of a string in C++ 
#include<iostream>
#include<string>
using namespace std;

int count(string);

int main()
{
string str;
cout << "Enter a string: ";
getline(cin,str);
cout << "\nString: " << str << endl;
cout << count(str) << endl;

return 0;

}

int count(string s){
if(s == "")
  return 0;
if(s.length() == 1)
  return 1;
else
    return (s.length());

}

4
你认为count(string)有什么string::length()没有的功能吗?除了无谓地多制作一份字符串副本以及在字符串长度超过20亿字符时返回负值之外。 - Eclipse

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接