如何从C中的字符串打印出其他所有字符?

时间:2018-08-23 05:04:08

标签: c string

从C中的字符串中打印出所有其他字符的最简单方法?我已经尝试使用

遍历数组
int main (void) 


for(int i = 0; i < strlen(input); i+=2)
{
    word[i] += input[i];
}

1 个答案:

答案 0 :(得分:6)

为什么不只在循环中打印它?

for(int i = 0; i < strlen(input); i+=2)
{
    putchar(input[i]);
}

如果仅要将每个第二个字符复制到另一个数组中,则您的错误是使用相同的索引word[i] += input[i];

并如@bcperth所述,也使用+ =运算符代替常规分配'='

您应该做的是:

word[i/2] = input[i];


#include <stdio.h>
#include <string.h>

int main(void) {
    char* p = "hello world";
    char s[32] = "";

    for(int i = 0; i < strlen(p); i+=2){
        putchar(p[i]);
        s[i/2]=p[i];
    }

    printf("\n\n2nd option\n%s", s);
    return 0;
}

输出:

hlowrd

2nd option
hlowrd
相关问题