C语言 获取 C 字符串中索引引用的字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4475948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:23:12  来源:igfitidea点击:

Get a character referenced by index in a C string

c

提问by Honza Pokorny

I have a string.

我有一个字符串。

char foo[] = "abcdefgh";

I would like to write a forloop, and one by one print out all of the characters:

我想写一个for循环,把所有的字符一一打印出来:

a
b
c

etc.

等等。

This is in C.

这是在 C 中。

回答by

Ok, well, this is a question so I'm going to answer it, but my answer is going to be slightly unusual:

好吧,这是一个问题,所以我要回答它,但我的回答会有点不寻常:

#include <stdio.h>

int main(int argc, char** argv)
{
    char string[] = "abcdefghi";
    char* s;

    for ( s=&string[0]; *s != '
void main(int argc, char** argv)
{
    char foo[] = "abcdefgh"; 
    int len = strlen(foo);
    int i = 0;
    for (i=0; i < len; i++)
    {
        printf("%c\n", foo[i]);
    }
    return 0;
}
'; s++ ) { printf("%c\n", *s); } return 0; }

This is notthe simplest way to achieve the desired outcome; however, it does demonstrate the fundamentals of what a string is in C. I shall leave you to read up on what I've done and why.

不是实现预期结果的最简单方法;然而,它确实展示了 C 中字符串的基本原理。我会让你阅读我所做的以及为什么。

回答by Honza Pokorny

int main(int argc, char *argv[])
{
   char foo[] = "abcdefgh";
   int len = sizeof(foo)/sizeof(char);
   int i = 0;
   for (i=0; i < len; i++) {
      printf("%c\n", foo[i]);
   }
   return 0;
}

回答by Nick Masao

Yet another way

又一种方式

##代码##