查找字符串的长度[重复]

问题描述 投票:1回答:3

可能重复: C++ String Length?

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

c++ string stdstring string-length
3个回答
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();
© www.soinside.com 2019 - 2024. All rights reserved.