实现求字符串长度的C++代码
时间: 2024-05-10 16:21:04 浏览: 8
```
#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;
}
```
相关问题
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;
}
```
string中求字符串长度c++
在 C++ 中,可以使用 `std::string` 的 `length()` 或 `size()` 方法来获取字符串的长度。以下是示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
int length = str.length(); // 或者使用 str.size();
std::cout << "字符串长度: " << length << std::endl;
return 0;
}
```
上述代码中,我们创建了一个名为 `str` 的 `std::string` 对象,并使用 `length()` 方法获取字符串的长度。然后,我们将结果打印到控制台上。输出将是:
```
字符串长度: 13
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)