Q
查找長度
1
A
回答
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
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();
相關問題
- 1. 查找陣列長度incakephp
- 2. 查找公鑰的長度
- 3. 查找std :: wstring的長度
- 4. 查找曲目按長度
- 5. 查找包含其自身長度的字符串的長度?
- 6. 使用面積和周長查找長度和寬度
- 7. 查找三次B樣條的長度
- 8. 查找C#中的MP3長度
- 9. 在mongodb中查找數組的長度
- 10. 如何查找char數組的長度?
- 11. 查找字符串的長度
- 12. 在JAVA中查找行的長度
- 13. 查找varchar(max)列的長度
- 14. 使用VBA查找行的長度
- 15. 查找一個XSTRING的長度
- 16. 如何查找數組類的長度?
- 17. JSON - 查找對象的長度
- 18. c,查找指針數組的長度
- 19. 如何查找JSON對象的長度
- 20. 查找最長的字符串名稱和長度
- 21. 在列中查找長度最長的字段
- 22. 如何查找表中長列的長度
- 23. 在不使用長度屬性的情況下查找數組的長度
- 24. 在nginx.conf文件中查找強度的長度
- 25. 查找2D陣列的寬度具有零長度
- 26. 查找家長UIActionSheet
- 27. 找到分區的長度
- 28. ElasticSearch查找基數查詢中的總長度
- 29. 用於查找值系列長度的SQL查詢
- 30. 串長度以找到重複節點的長度
我傾向於downvote這是因爲標籤是C++ ... – 2012-08-10 00:16:07
在C++中,它會沒有。 –
stonemetal
2012-08-10 00:16:21
這裏不是權威,但我相信也是有效的。實際上,我在http://www.cplusplus.com/reference/clibrary/cstring/strlen/ –
NotGaeL
2012-08-10 00:35:40