我在这个c程序中遇到错误

时间:2015-03-26 12:43:40

标签: c string ascii

我正在尝试实现这个c程序,我想扩展字符串 例如a-z到b c d ... z等 当我把输入字符串作为a-z我没有得到o / p但当我使用输入字符串az或不使用-我得到所需的o / p

#include<stdio.h>
main()
{
    char s1[20] = "a   z", s2[10], s3[30];
    int k = 0, i = 0;
    while (s1[i] != '\0')
    {
        if((s1[i] >= 65 && s1[i]<= 90) || (s1[i] >= 97 && s1[i]<= 122))
            s2[k]=s1[i];
        i++;  k++;
    }
    s2[k] = '\0';
    for (int m = s2[0] ; m <= s2[1] ; m++)
       printf("%c ",m);
}

4 个答案:

答案 0 :(得分:0)

您应该只在需要时更新'k'位置:

if((s1[i] >= 65 && s1[i]<= 90) || (s1[i] >= 97 && s1[i]<= 122)) {
    s2[k]=s1[i];
    k++;
}

i++; 

此外,您的目标数组s2(存储扩展字母的数组)应至少为27(26+ \ 0)。

答案 1 :(得分:0)

为什么这么麻烦?这段小代码可以满足您的需求:

#include<stdio.h>

int main()
{
    char s1[4] = "a-z";
    int m;

    for(m=s1[0]; m<=s1[2]; m++)
    {
        printf("%c ",m);
    }

    return 0;
}

答案 2 :(得分:0)

根据您的需要:

char s1[20] = "a-z", s2[10],s3[30]; //a-z are now 3 characters


for(int m=s2[0]; m<=s2[2] ; m++) //loop for 3rd character i.e. "z".
   printf("%c ",m);
  

输出:a b c d e f g h i j k l m n o p q r s t u v w x y z

答案 3 :(得分:0)

#include <stdio.h>

char *expand(char *out, const char *in){
    size_t i, j;
    for(j = i = 0; in[i] != '\0'; ++i){
        if(in[i] != '-' || i == 0 || in[i+1] == '\0' || (unsigned char)in[i-1] >= (unsigned char)in[i+1]){
            out[j++] = in[i];
        } else {
            unsigned char ch_s = in[i-1] + 1, ch_e = in[i+1];
            while(ch_s < ch_e){
                out[j++] = ch_s++;
            }
        }
    }
    out[j] = '\0';
    return out;
}

int main(void){
    const char *test[] = {
        "a-z", "-a-e", "A-Z0-9", "a-a", "z-a", "a-e-g", "this is test-print"
    };
    char expanded[128];
    size_t i, size = sizeof(test)/sizeof(*test);
    for(i = 0; i < size; ++i){
        printf("%s expand to %s\n", test[i], expand(expanded, test[i]));
    }
    return 0;
}
#if 0
a-z expand to abcdefghijklmnopqrstuvwxyz
-a-e expand to -abcde
A-Z0-9 expand to ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
a-a expand to a-a
z-a expand to z-a
a-e-g expand to abcdefg
--/ expand to -./
test-print expand to test-print
#endif