【C语言】关于遍历字符串的三种方法

写在前面的话:
1. 版权声明:本文为博主原创文章,转载请注明出处!
2. 博主是一个小菜鸟,并且非常玻璃心!如果文中有什么问题,请友好地指出来,博主查证后会进行更正,啾咪~~
3. 每篇文章都是博主现阶段的理解,如果理解的更深入的话,博主会不定时更新文章。
4. 本文最后更新时间:2020.7.8

正文开始

这里介绍C语言遍历字符串的三种方法。

1. for循环(字符数组)

#include <stdio.h>
#include <string.h>

#define MAX_SIZE 1024

int main()
{
    char src[MAX_SIZE] = {0};
    int len;

    printf("Please input string : ");
    gets(src);

    len = strlen(src);

    printf("string = ");

    for (int i = 0; i < len; i++)
    {
        printf("%c", src[i]);
    }
    printf("\n");

    return 0;
}
运行结果:
Please input string : abcdefg123456   
string = abcdefg123456
在这里我们首先利用了strlen函数测量字符数组的长度,然后用for循环遍历字符串,将输入的字符串的内容一个字符一个字符输出。

2. while循环(字符数组)

#include <stdio.h>
#include <string.h>

#define MAX_SIZE 1024

int main()
{
    char src[MAX_SIZE] = {0};
    int i = 0;

    printf("Please input string : ");
    gets(src);

    printf("string = ");

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

    return 0;
}
运行结果:
Please input string : congcong123456
string = congcong123456
由于输入的字符串的长度是未知的,然而遍历字符串的时候需要用到循环,所以,当循环次数未知时,最好使用while语句。

3. while循环(指针)

#include <stdio.h>
#include <string.h>

#define MAX_SIZE 1024

int main()
{
    char src[MAX_SIZE] = {0};
    char *temp = src;

    printf("Please input string : ");
    gets(src);

    printf("string = ");

    while (*temp != '\0')
    {
        printf("%c", *temp);
        temp++;
    }
    printf("\n");

    return 0;
}
运行结果:
Please input string : congcong123
string = congcong123

在这里我们首先定义了一个指针变量,指向数组的首地址,那为什么要定义这个指针变量呢?为什么不直接用“src++;”呢?

首先,我们要知道的是数组名代表了什么:
1. 指针常量
2. 数组首元素的地址

既然数组名代表了指针常量,常量怎么可以自增呢?所以不可以用“src++;”,如果使用“src++;”,那么在编译时便会报错“错误:自增运算中的左值无效”。

以上为遍历字符串的三种方法,希望我们以后可以熟练地运用这三种方法遍历字符串。

  • 36
    点赞
  • 141
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值