我目前正在 K&R C 中进行练习 3-3,我很困惑为什么我的解决方案不起作用。本练习的目标是传递两个字符串,当您遇到“a-z”或“0-9”之类的内容时,您将打印出这两个字符的完整列表。这是我当前的解决方案:
#include <stdio.h>
#include <stdlib.h>
char* expand(char s1[], char s2[]);
int main(){
char s1[100] = {"a-z is higher on the ascii table than 0-9\0"};
char s2[200];
expand(s1, s2);
printf("%s\n", s2);
}
char* expand(char s1[], char s2[]){
char temp;
char temp2;
for(int i = 0; s1[i] != '\0'; i++){
if(s1[i] == '-'){
temp = s1[i-1];
temp2 = s1[i+1];
for(int j = temp + 1; j < temp2; j++){
s2[i] = j;
i++;
}
}
else
{
s2[i] = s1[i];
}
}
return s2;
}
如有任何帮助,我们将不胜感激,谢谢!
最佳答案
这应该是@user3386109建议的代码的循环部分
int i2 = 0;
for(int i = 0; s1[i] != '\0'; i++){
if(s1[i] == '-' && i != 0 && s[i+1] != '\0'){
temp = s1[i-1];
temp2 = s1[i+1];
for(int j = temp + 1; j < temp2; j++){
s2[i2] = j;
i2++;
}
}
else s2[i2++] = s1[i];
}
如果发生扩展,则在实际输入 s1
上迭代时 i
会出现乱码。因此将其隔离。
关于c - K&R C 练习 3-3 编辑数组中的 char 元素不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46134706/