gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:31:20 26 4
gpt4 key购买 nike

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

遍历数组
int main (void) 


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

最佳答案

为什么不直接在循环中打印呢?

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

如果您只想将每个第 2 个字符复制到另一个数组中,您的错误是使用了相同的索引 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

关于c - 我如何打印出 C 中字符串中的所有其他字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51978650/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com