【发布时间】:2012-08-07 06:55:48
【问题描述】:
【问题讨论】:
标签: c++ string stdstring string-length
【问题讨论】:
标签: c++ string stdstring string-length
您可以使用<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 <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
【讨论】:
<string.h> 是有效的 C++,但我认为 <cstring> 是首选。
在 C++ 中:
#include <iostream>
#include <string>
std::string s;
std::cin >> s;
int len = s.length();
【讨论】:
提示:
std::string str;
std::cin >> str;
std::cout << str.length();
【讨论】: