c语言

c语言遍历字符串的方法是什么

小亿
208
2024-05-14 17:38:14
栏目: 编程语言
C语言开发专用服务器,限时0元免费领! 查看>>

在C语言中,可以使用循环来遍历字符串。其中最常用的方法是使用for循环和while循环。

使用for循环遍历字符串:

#include <stdio.h>

int main() {
    char str[] = "Hello, World!";
    int i;

    for(i = 0; str[i] != '\0'; i++) {
        printf("%c", str[i]);
    }

    return 0;
}

使用while循环遍历字符串:

#include <stdio.h>

int main() {
    char str[] = "Hello, World!";
    int i = 0;

    while(str[i] != '\0') {
        printf("%c", str[i]);
        i++;
    }

    return 0;
}

这两种方法都会逐个访问字符串中的字符,直到遇到字符串结束符\0为止。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

相关推荐:c语言怎么遍历字符串

0
看了该问题的人还看了