用C++写一函数,实现两个字符串的比较。要求不可调用strcmp函数,而是自己去实现。函数原型为 int strcmp(char *p1,*p2);设p1指向字符串s1,p2指向字符串s2。,当s1=s2时,返回值为0,否则,返回它们二者第一个不同字符的ASCII码差值,如果s1>s2,则输出正值,如果s1<s2,则输出负值。
时间: 2024-02-15 22:02:12 浏览: 28
好的,我来给出一个C++实现的`strcmp`函数。基本思路是逐个比较两个字符串中对应位置的字符,如果出现不同的字符,则返回这两个字符的ASCII码差值。如果其中一个字符串比另一个短,则在短字符串结尾处补0进行比较。如果两个字符串完全相同,则返回0。以下是代码示例:
```C++
int strcmp(char *p1, char *p2) {
while (*p1 && (*p1 == *p2)) {
p1++;
p2++;
}
return *p1 - *p2;
}
```
其中`while`循环中的条件`*p1 && (*p1 == *p2)`表示只要两个字符串中对应位置的字符相同且`*p1`不为0(即字符串没有结束),就继续比较下一位。最后返回`*p1 - *p2`的值,即两个字符串第一个不同字符的ASCII码差值。
需要注意的是,如果输入的两个字符串长度不同,则要在短字符串结尾处补0,否则会出现不可预测的结果。另外,为了避免函数名与标准库中的`strcmp`函数冲突,我们可以将函数名改为`my_strcmp`等。
希望对你有所帮助!
相关问题
在c++中,不使用strcmp函数实现字符串的比较大小
在 C++ 中,可以使用运算符重载的方式实现字符串的比较大小,以下是一个示例:
```c++
#include <iostream>
#include <cstring>
using namespace std;
class MyString {
private:
char *str;
int len;
public:
MyString(const char *s = "") {
len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
}
~MyString() {
delete[] str;
}
bool operator<(const MyString &other) const {
return strcmp(str, other.str) < 0;
}
bool operator>(const MyString &other) const {
return strcmp(str, other.str) > 0;
}
bool operator==(const MyString &other) const {
return strcmp(str, other.str) == 0;
}
};
int main() {
MyString s1("abc");
MyString s2("def");
if (s1 < s2) {
cout << "s1 < s2" << endl;
} else if (s1 > s2) {
cout << "s1 > s2" << endl;
} else {
cout << "s1 == s2" << endl;
}
return 0;
}
```
在这个示例中,我们定义了一个 MyString 类,其中重载了 `<`, `>` 和 `==` 运算符用于字符串的比较大小。这样,我们就可以直接使用运算符进行比较,而不需要调用 strcmp 函数。
用c++写程序,实现两个字符串比较的自定义版
以下是一个用 C 语言实现的字符串比较自定义版的示例程序:
``` c
#include <stdio.h>
int my_strcmp(char *s1, char *s2) {
while (*s1 != '\0' && *s2 != '\0') { // 比较两个字符串的每个字符
if (*s1 != *s2) {
return (*s1 - *s2); // 如果不相等,返回它们的 ASCII 码差值
}
s1++;
s2++;
}
return (*s1 - *s2); // 如果到达了字符串末尾,返回它们的长度差值
}
int main() {
char str1[100], str2[100];
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
int result = my_strcmp(str1, str2);
if (result == 0) {
printf("两个字符串相等\n");
}
else if (result > 0) {
printf("第一个字符串大于第二个字符串\n");
}
else {
printf("第一个字符串小于第二个字符串\n");
}
return 0;
}
```
这个程序中,我们定义了一个名为 `my_strcmp` 的函数,接受两个指向字符数组的指针 `s1` 和 `s2`,并返回它们的比较结果。在这个函数中,我们使用了一个 `while` 循环来比较两个字符串的每个字符,如果它们不相等,就返回它们的 ASCII 码差值;如果到达了字符串末尾,就返回它们的长度差值。
在 `main` 函数中,我们使用 `scanf` 函数从标准输入读取两个字符串,并调用 `my_strcmp` 函数来比较它们。最后,根据比较结果输出相应的信息。