2012-08-10 89 views
1

可能重複:
C++ String Length?查找長度

我真的需要幫助了。如何接受字符串作爲輸入並查找字符串的長度?我只想要一個簡單的代碼來了解它是如何工作的。謝謝。

回答

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 
+0

我傾向於downvote這是因爲標籤是C++ ... – 2012-08-10 00:16:07

+0

在C++中,它會沒有。 – stonemetal 2012-08-10 00:16:21

+0

這裏不是權威,但我相信也是有效的。實際上,我在http://www.cplusplus.com/reference/clibrary/cstring/strlen/ – NotGaeL 2012-08-10 00:35:40

4

提示:

std::string str; 
std::cin >> str; 
std::cout << str.length(); 
2
在C++

#include <iostream> 
#include <string> 

std::string s; 
std::cin >> s; 
int len = s.length();