【问题标题】:how do i print out every other character from a string in C?如何从 C 中的字符串中打印出所有其他字符?
【发布时间】:2018-08-23 05:04:07
【问题描述】:

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

遍历数组
int main (void) 


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

【问题讨论】:

  • strlen(p)移出循环,否则每次迭代都会被一次又一次调用
  • 你有其他语言的背景,不是吗?我推荐ericlippert.com/2014/03/21/find-a-simpler-problem 例如通过以下步骤: 1)在 C 中找到一个 HelloWorld 并使其运行 2)将其更改为逐字符打印。 3) 更改为将位置增加 2 而不是 1
  • @phuclv 理论上是的。编译器在过去就是这样做的。现在编译器应该能够分辨出input 没有被循环改变并且循环中没有指针是别名,因此编译器只需要对strlen 表达式求值一次。
  • @Lundin no, most compilers won't optimize that 并且仍然在每个循环中再次调用该函数
  • @Lundin,这仅适用于某些已知功能。否则编译器无法知道返回值是否会在每次迭代中发生变化..

标签: c string


【解决方案1】:

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

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

【讨论】:

  • 值得注意的是,目标字符串大小限制为32字节,这意味着输入缓冲区大于63个字符会导致程序崩溃。另请注意, strlen(p) 在每个 for 循环中都被评估,并且实际上是恒定的。因此最好在 for 循环之前获取此值并将其用作常量。
猜你喜欢
  • 2017-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-24
  • 1970-01-01
  • 2020-03-23
相关资源
最近更新 更多