Linux 拨号vps windows公众号手机端

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

lewis 1年前 (2024-05-09) 阅读数 14 #程序编程
文章标签 c语言

在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为止。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门