编写程序求任意一个字符串的长度,但不使用string函数
时间: 2023-06-17 22:05:46 浏览: 60
可以使用以下方法来求一个字符串的长度:
```c++
#include <iostream>
int main()
{
const char* str = "Hello, world!";
int len = 0;
while (*str != '\0')
{
++len;
++str;
}
std::cout << "The length of the string is: " << len << std::endl;
return 0;
}
```
在这个程序中,我们使用一个指向字符常量的指针来表示字符串。然后我们使用一个 while 循环来遍历字符串中的每一个字符,并在每次循环中将长度加 1。当我们遍历到字符串的结尾(即遇到了空字符 '\0')时,循环结束,此时字符串的长度就是 len 的值。
相关问题
编写一个自定义函数返回一个任意字符串的长度Python
当然可以!以下是一个示例代码,它定义了一个名为`get_string_length`的函数,接受一个字符串作为输入,并返回该字符串的长度:
```python
def get_string_length(input_string):
return len(input_string)
# 示例用法
string = "Hello, World!"
length = get_string_length(string)
print(length) # 输出:13
```
在上述代码中,`get_string_length`函数使用了内置函数`len()`来获取输入字符串的长度,并将其作为返回值。你可以将任意字符串作为参数传递给这个函数,它会返回对应字符串的长度。
注意:这只是一个简单的示例,你可以根据自己的需求对函数进行扩展和修改。
编写一个自定义函数返回一个任意字符串的长度(不能使用len函数)Python
如果不能使用内置的`len()`函数,你可以编写一个自定义函数来计算字符串的长度。以下是一个示例代码:
```python
def get_string_length(input_string):
count = 0
for _ in input_string:
count += 1
return count
# 示例用法
string = "Hello, World!"
length = get_string_length(string)
print(length) # 输出:13
```
在上述代码中,我们创建了一个名为`get_string_length`的函数。它使用循环遍历字符串中的每个字符,并通过`count`变量进行计数。最后,返回计数值作为字符串的长度。
请注意,这只是一种替代方法,如果没有特殊要求,通常使用内置的`len()`函数更为简单和高效。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.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)