【问题标题】:Find length of string [duplicate]查找字符串的长度[重复]
【发布时间】:2012-08-07 06:55:48
【问题描述】:

可能重复:
C++ String Length?

我现在真的需要帮助。如何接受字符串作为输入并找到字符串的长度?我只想要一个简单的代码来了解它是如何工作的。谢谢。

【问题讨论】:

    标签: c++ string stdstring string-length


    【解决方案1】:

    您可以使用<string.h> 中的strlen(mystring)。它返回字符串的长度。

    记住:C 中的字符串是一个以字符 '\0' 结尾的字符数组。保留足够的内存(整个字符串 + 1 个字节适合数组),字符串的长度将是从指针 (mystring[0]) 到 '\0' 之前的字符的字节数

    #include <string.h> //for strlen(mystring)
    #include <stdio.h> //for gets(mystring)
    
    char mystring[6];
    
    mystring[0] = 'h';
    mystring[1] = 'e';
    mystring[2] = 'l';
    mystring[3] = 'l';
    mystring[4] = 'o';
    mystring[5] = '\0';
    
    strlen(mystring); //returns 5, current string pointed by mystring: "hello"
    
    mystring[2] = '\0';
    
    strlen(mystring); //returns 2, current string pointed by mystring: "he"
    
    gets(mystring); //gets string from stdin: http://www.cplusplus.com/reference/clibrary/cstdio/gets/
    

    http://www.cplusplus.com/reference/clibrary/cstring/strlen/

    编辑:如 cmets 中所述,在 C++ 中,最好将 string.h 称为 cstring,因此编码 #include &lt;cstring&gt; 而不是 #include &lt;string.h&gt;

    另一方面,在 C++ 中,您还可以使用 C++ 特定的字符串库,它提供了一个字符串类,允许您将字符串作为对象使用:

    http://www.cplusplus.com/reference/string/string/

    这里有一个很好的字符串输入示例:http://www.cplusplus.com/reference/string/operator%3E%3E/

    在这种情况下,您可以通过以下方式声明一个字符串并获取其长度:

    #include <iostream>
    #include <string>
    
    string mystring ("hello"); //declares a string object, passing its initial value "hello" to its constructor
    cout << mystring.length(); //outputs 5, the length of the string mystring
    cin >> mystring; //reads a string from standard input. See http://www.cplusplus.com/reference/string/operator%3E%3E/
    cout << mystring.length(); //outputs the new length of the string
    

    【讨论】:

    • 我倾向于对此投反对票,因为标签是 C++...
    • 在 C++ 中是 而不是
    • 这里不是权威,但我相信 也是有效的。事实上,我在cplusplus.com/reference/clibrary/cstring/strlen 中指出的示例使用了它
    • &lt;string.h&gt; 是有效的 C++,但我认为 &lt;cstring&gt; 是首选。
    • @Luchian Grigore 我不知道它是否值得投反对票,但你是对的:我在用 C++ 编程时一直使用我的 C 包。我很懒,只有在节省时间和行数时才使用 C++ 细节,但事实并非如此。我刚刚对您的答案进行了投票,并更新了我的答案以包含正确的替代方案。
    【解决方案2】:

    在 C++ 中:

    #include <iostream>
    #include <string>
    
    std::string s;
    std::cin >> s;
    int len = s.length();
    

    【讨论】:

      【解决方案3】:

      提示:

      std::string str;
      std::cin >> str;
      std::cout << str.length();
      

      【讨论】:

        猜你喜欢
        • 2016-08-11
        • 1970-01-01
        • 1970-01-01
        • 2017-06-13
        • 2013-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-19
        相关资源
        最近更新 更多