比较两个字符串的大小,比较方法为对两个字符串从前往后逐个字符相比较(按ASCII码值大小比较),直到出现不同的字符或遇到字符串结束为止
时间: 2023-06-16 10:08:11 浏览: 123
可以使用以下的C++代码实现对两个字符串的大小比较:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int compareStrings(char str1[], char str2[]) {
int len1 = strlen(str1);
int len2 = strlen(str2);
int len = min(len1, len2);
for (int i = 0; i < len; i++) {
if (str1[i] > str2[i]) {
return 1;
} else if (str1[i] < str2[i]) {
return -1;
}
}
if (len1 > len2) {
return 1;
} else if (len1 < len2) {
return -1;
} else {
return 0;
}
}
int main() {
char str1[] = "abc";
char str2[] = "abd";
int result = compareStrings(str1, str2);
if (result == 1) {
cout << "str1 is greater than str2" << endl;
} else if (result == -1) {
cout << "str1 is less than str2" << endl;
} else {
cout << "str1 is equal to str2" << endl;
}
return 0;
}
```
在这个示例中,我们先计算出两个字符串的长度,然后使用min函数找出较短的字符串的长度。接着,我们逐个比较两个字符串对应位置的字符的ASCII码值大小,直到出现不同的字符或遇到字符串结束。最后,如果两个字符串长度不相等,则较长的字符串更大。如果两个字符串相等,则返回0。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![.rar](https://img-home.csdnimg.cn/images/20210720083646.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_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)