优化这段代码#include <stdio.h>#include <string.h>int main() { char str[100]; char oldChar, newChar; printf("Enter a string: "); fgets(str, 100, stdin); printf("Enter the old character: "); scanf("%c", &oldChar); printf("Enter the new character: "); scanf(" %c", &newChar); for (int i = 0; i < strlen(str); i++) { if (str[i] == oldChar) { str[i] = newChar; } } printf("New string: %s\n", str); return 0;}
时间: 2023-12-06 08:40:14 浏览: 45
这段代码本身并没有太大的问题,但是可以进行一些优化:
1. 使用puts代替printf输出字符串,可以避免出现格式化符号的错误。
2. 在输入oldChar和newChar时,使用getchar清除缓存区,避免fgets读取到多余的字符。
3. 在for循环中,将strlen(str)提取到一个变量中,避免每次循环都计算一次,提高效率。
下面是优化后的代码:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
char oldChar, newChar;
int len;
puts("Enter a string: ");
fgets(str, 100, stdin);
puts("Enter the old character: ");
scanf("%c", &oldChar);
getchar(); // 清除缓存区
puts("Enter the new character: ");
scanf("%c", &newChar);
getchar(); // 清除缓存区
len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] == oldChar) {
str[i] = newChar;
}
}
puts("New string: ");
puts(str);
return 0;
}
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](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)