我的下一个任务有问题。问题是:字典顺序,字符串,C++
让我们假设我们有一个字母A(c,a,b)。写功能:
int my_strcmp(char S1[], char S2[]);
它将比较字符数组S1和S2,写在A alpak。 结果应该是:
0
,如果S1 == S2
-1
,如果S1是字典顺序比S2
+1
较小,如果S1是字典顺序比S2
性能测试 - 大案例:
“aa
”“cc
”=> 1
“ac
”, “a
”=> 1
“c
” “ac
”=> -1
“bc
” “ab
”=> 1
“bc
” “ac
”=> 1
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>
#include <iostream>
#include <string>
#include <algorithm>
#define T_SIZE 1001
int my_strcmp(char S1[], char S2[]);
int compCh(char a, char b);
int main(){
int t;
char S1[T_SIZE], S2[T_SIZE];
scanf_s("%d", &t);
while(t) {
std::cin.getline(S1,T_SIZE,' ');
std::cin.getline(S2, T_SIZE);
printf("%d\n", my_strcmp(S1, S2));
t--;
}
system("pause");
return 0;
}
int compCh(char a, char b) {
int x, y;
switch (a) {
case 'c':
x = 0;
break;
case 'a':
x = 1;
break;
default:
x = 2;
break;
}
switch (b) {
case 'c':
y = 0;
break;
case 'a':
y = 1;
break;
default:
y = 2;
break;
}
return (x - y);
}
int my_strcmp(char S1[], char S2[]) {
for (int i = 0; (i<std::min(strlen(S1), strlen(S2))); i++) {
if (i == 0) {
if (compCh(S1[i+1], S2[i]) == 0) {
continue;
}
else if (compCh(S1[i+1], S2[i]) < 0) {
return -1;
}
else {
return 1;
}
}
else {
if (compCh(S1[i], S2[i]) == 0) {
continue;
}
else if (compCh(S1[i], S2[i]) < 0) {
return -1;
}
else {
return 1;
}
}
}
if (strlen(S1) > strlen(S2)) {
return 1;
}
else {
return -1;
}
}
我不知道为什么它现在正在工作。我想的是,在当
my_strcmp
函数I == 0,则S1 [I]将等于一些奇怪看不见符号。即使tho,用if语句改变函数后,如果我== 0,捕捉程序仍然无法正常工作。我不知道哪里出错,因为这个程序正在通过在线评审程序进行检查。
我并不是要求现成的答案,但请指出我犯的错误。
你确定当一个字符串的前缀长时,字符串应该比较小吗? – Deduplicator 2014-12-19 12:01:32
在调试器中运行你的程序,并逐行浏览代码,看看它在做什么。 – 2014-12-19 12:02:56
更正了这个i == 0。由于某些原因,即使S1 =“a”,那么我可能得到S1 [1],这将等于“a”。它只在for循环的第一次运行中可行。接下来的似乎很好。 – Setzo 2014-12-19 12:06:29