我目前正在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;
}
任何帮助将不胜感激,谢谢!
答案 0 :(得分:1)
这应该是@ 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];
}
如果发生扩展,i
会因实际输入s1
进行迭代而出现乱码。因此隔离它。