【问题标题】:How to find the lenght of the word in C++? [duplicate]如何在 C++ 中找到单词的长度? [复制]
【发布时间】:2021-04-11 04:34:46
【问题描述】:

我们有一些词,我们应该确定它的长度。我怎样才能做到这一点? 示例输入:“你好” - 不带引号; 示例输出:5

【问题讨论】:

标签: c++ string word


【解决方案1】:
string str;
cin>>str;
//use this
cout<<str.length();
//or use this
cout<<str.size();

它们都可以正常工作。

【讨论】:

    【解决方案2】:

    如果输入包含在 std::string 中,您可以找到 Ravi 所述的长度。 如果它是一个 C 字符串,你可以找到长度

    int len = strlen(INPUT);
    

    在 C/C++ 中,大写通常用于常量,因此最好将字符串命名为 input,而不是 INPUT

    【讨论】:

      【解决方案3】:

      您可以使用input.length() or input.size()

      或者你可以使用这个简单的循环。

       for (i = 0; str[i]; i++) 
              ; 
          cout << i << endl; 
      

      【讨论】:

      • 不建议新手滚动他们自己版本的标准函数。它完全没有必要。
      • 该循环执行std::strlen 的操作,但std::string 允许包含额外的空字符,因此它与std::string::length 不同。
      【解决方案4】:

      在 C++ 中有一个函数可以求长度。 您可以尝试使用:

      input.length()
      

      还请记住,您需要包括:

      #include <iostream>
      using namespace std;
      

      参考这个文件: https://www.w3schools.com/cpp/cpp_strings_length.asp

      【讨论】:

      • 您无需包含 iostream 即可使用 std::string。而且你不应该使用using namespace std;,它是bad practice
      猜你喜欢
      • 2014-05-24
      • 1970-01-01
      • 2013-03-26
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      • 2013-09-10
      • 2022-12-04
      • 1970-01-01
      相关资源
      最近更新 更多