How to get the number of characters in a std::string?

前端 未结 12 1008
既然无缘
既然无缘 2020-11-28 03:52

How should I get the number of characters in a string in C++?

12条回答
  •  被撕碎了的回忆
    2020-11-28 04:30

    It might be the easiest way to input a string and find its length.

    // Finding length of a string in C++ 
    #include
    #include
    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());
    
    }
    

提交回复
热议问题