求一个字符串的长度的c++代码
时间: 2024-02-13 11:01:26 浏览: 24
可以使用 C++ 标准库中的 `string` 类型的 `length()` 方法来获取字符串的长度,示例代码如下:
```c++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cout << "请输入一个字符串:";
getline(cin, str);
int len = str.length();
cout << "字符串长度为:" << len << endl;
return 0;
}
```
这个程序会提示用户输入一个字符串,然后使用 `length()` 方法获取字符串的长度并输出。
相关问题
c++中求字符串长度的代码
以下是两种C++中求字符串长度的代码:
1.使用string类的length()函数
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello World!";
int len = str.length();
cout << "The length of the string is: " << len << endl; // 输出:The length of the string is: 12
return 0;
}
```
2.使用C语言库函数strlen()
```cpp
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[] = "Hello World!";
int len = strlen(str);
cout << "The length of the string is: " << len << endl; // 输出:The length of the string is: 12
return 0;
}
```
实现求字符串长度的C++代码
```
#include <stdio.h>
int strlen(char str[]) {
int len = 0;
while (str[len] != '\0') {
len++;
}
return len;
}
int main() {
char str[] = "Hello, world!";
int len = strlen(str);
printf("The length of the string is %d\n", len);
return 0;
}
```