如何遍历C中的字符串? [英] How to iterate over a string in C?

查看:17
本文介绍了如何遍历C中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我正在尝试这个:

#include <stdio.h>

int main(int argc, char *argv[]) {

    if (argc != 3) {

        printf("Usage: %s %s sourcecode input", argv[0], argv[1]);
    }
    else {
        char source[] = "This is an example.";
        int i;

        for (i = 0; i < sizeof(source); i++) {

            printf("%c", source[i]);
        }
    }

    getchar();

    return 0;
}

这也不起作用:

char *source = "This is an example.";
int i;

for (i = 0; i < strlen(source); i++){

    printf("%c", source[i]);
}

我得到了错误

Test.exe 中 0x5bf714cf (msvcr100d.dll) 处未处理的异常:0xC0000005:在位置 0x00000054 读取时访问冲突.

Unhandled exception at 0x5bf714cf (msvcr100d.dll) in Test.exe: 0xC0000005: Access violation while reading at position 0x00000054.

(大致从德语翻译)

那么我的代码有什么问题?

So what's wrong with my code?

推荐答案

你想要:

for (i = 0; i < strlen(source); i++) {

sizeof 为您提供指针的大小,而不是字符串.但是,如果您将指针声明为数组,它会起作用:

sizeof gives you the size of the pointer, not the string. However, it would have worked if you had declared the pointer as an array:

char source[] = "This is an example.";

但是如果将数组传递给函数,它也会衰减为指针.对于字符串,最好始终使用 strlen.并注意其他人所说的关于将 printf 更改为使用 %c 的内容.而且,考虑到 mmyers 对效率的评论,最好将 strlen 的调用移出循环:

but if you pass the array to function, that too will decay to a pointer. For strings it's best to always use strlen. And note what others have said about changing printf to use %c. And also, taking mmyers comments on efficiency into account, it would be better to move the call to strlen out of the loop:

int len = strlen(source);
for (i = 0; i < len; i++) {

或重写循环:

for (i = 0; source[i] != 0; i++) {

这篇关于如何遍历C中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆