1

可能重复:
C++ 字符串长度?

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

4

3 回答 3

4

暗示:

std::string str;
std::cin >> str;
std::cout << str.length();
于 2012-08-10T00:14:03.580 回答
2

在 C++ 中:

#include <iostream>
#include <string>

std::string s;
std::cin >> s;
int len = s.length();
于 2012-08-10T00:14:12.983 回答
1

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

请记住: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/

编辑:如评论中所述,在 C++ 中,最好将 string.h 称为 cstring,因此编码#include <cstring>而不是#include <string.h>.

另一方面,在 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
于 2012-08-10T00:12:03.533 回答