创建字符串输出两个字符串长度
时间: 2023-11-09 09:05:55 浏览: 39
可以使用 len() 函数来获取一个字符串的长度,并使用字符串拼接符号 + 将两个长度拼接在一起。例如:
```
str1 = "Hello"
str2 = "World"
lengths = "Length of str1: " + str(len(str1)) + ", length of str2: " + str(len(str2))
print(lengths)
```
输出结果为:
```
Length of str1: 5, length of str2: 5
```
相关问题
输入两个字符串输出较大者C语言
以下是输入两个字符串输出较大者的C语言代码:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100], str2[100];
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
if (strlen(str1) > strlen(str2))
{
printf("较大的字符串是:%s\n", str1);
}
else if (strlen(str1) < strlen(str2))
{
printf("较大的字符串是:%s\n", str2);
}
else
{
printf("两个字符串长度相等。\n");
}
return 0;
}
```
C++比较两个字符串长度的函数
以下是比较两个字符串长度的函数实现:
```C
int stringLength(char* str1, char* str2) {
int len1 = 0, len2 = 0;
// 计算第一个字符串的长度
while (*str1 != '\0') {
len1++;
str1++;
}
// 计算第二个字符串的长度
while (*str2 != '\0') {
len2++;
str2++;
}
if (len1 == len2)
return 0;
else if (len1 < len2)
return -1;
else
return 1;
}
```
这个函数接受两个指向字符串的指针作为参数,分别计算这两个字符串的长度并比较它们的大小。如果两个字符串的长度相等,则返回0。如果第一个字符串的长度小于第二个字符串的长度,则返回-1。如果第一个字符串的长度大于第二个字符串的长度,则返回1。该函数使用了指针来遍历字符串,并使用了while循环和if语句来实现逻辑。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)