【问题描述】输入一个字符,再输入一个以"#"结束的字符串(少于80个字符),在字符串中查找该字符。如果找到,则输出该字符在字符串中所对应的最大下标,下标从0开始;否则输出“Not Found”。试编写相应程序。
【样例输入】
a banana#
【样例输出】
5
#include <stdio.h>
int main() {
char target;
char str[80];
char c;
int i = 0;
int maxIndex = -1;
int j;
scanf(" %c", &target);
while ((c = getchar()) != '#') {
str[i++] = c;//i++在最后执行
}
str[i] = '\0'; //末尾标识符
for ( j = 0; str[j] != '\0'; j++) {
if (str[j] == target) {
maxIndex = j-1;//原始代码
}
}
if (maxIndex != -1) {
printf("%d\n", maxIndex);
} else {
printf("Not Found\n");
}
return 0;
}
上述代码虽然能够正常运行,但是如果仔细端详,定然不能理解其中的“maxIndex = j-1”为什么要这么写,按照道理来讲不是应该写为“maxIndex = j”的形式吗,为什么要-1.?这里给出如下解释
#include <stdio.h>
int main() {
char target;
char str[80];
char c;
int i = 0;
int maxIndex = -1;
int j;
scanf(" %c", &target);
// scanf()
//函数以空格或回车符做结束读取标志,空格和回车符会留在缓冲区。
//因此我们在使用scanf()函数的时候就会遇到两大问题
//第一:不能直接输入空格;
//第二:遗留的回车符会对后面的读取造成影响
//前面的scanf()在读取输入时会在缓冲区中留下一个字符’\n’(输入完按回车键所致),
//所以如果不在此加一个getchar()把这个回车符取走的话
getchar();
//就容易造成读取错位的问题
//此时缓存区为空
while ((c = getchar()) != '#') {
str[i++] = c;//i++在最后执行
}
str[i] = '\0'; //末尾标识符
for ( j = 0; str[j] != '\0'; j++) {
if (str[j] == target) {
maxIndex = j;//符合常理逻辑
}
}
if (maxIndex != -1) {
printf("%d\n", maxIndex);
} else {
printf("Not Found\n");
}
return 0;
}