查找字符串的长度
Find length of string
可能的重复项:
C++字符串长度?
我现在真的需要帮助。如何接受字符串作为输入并找到字符串的长度?我只是想要一个简单的代码,只是为了知道它是如何工作的。谢谢。
提示:
std::string str;
std::cin >> str;
std::cout << str.length();
在 C++ 中:
#include <iostream>
#include <string>
std::string s;
std::cin >> s;
int len = s.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] = ' ';
strlen(mystring); //returns 5, current string pointed by mystring: "hello"
mystring[2] = ' ';
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
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 按类型与字符串查找对象
- 使用C RTTI(内置)通过字符串查找功能指针
- 关于获取行和字符串查找函数的问题
- 字符串查找方法找不到第一字母
- C++ 字符串.查找()
- 遇到字符串::查找的问题
- 将一个数组作为子字符串查找到另一个数组中
- 字符串查找第一个非的 C++ 问题
- 如何将通配符与字符串::查找一起使用
- 字符串::查找问题 (C++)
- 性能标准::strstr vs. 标准::字符串::查找
- C++字符串::查找崩溃应用程序
- 使用字符串查找单词的正确方法是什么
- 如何在<string>没有 std::string 中介的情况下制作一个支持通过 C 字符串查找的集合?
- 使用C++根据行中的第一个字符串查找行(仅一个)
- Borland字符串::查找bug
- std::map如何通过字符串查找元素
- 字符串查找函数返回奇数
- 如何使用子字符串查找数字行的正确部分