字符串遍历

在python中遍历一个字符串中的每个字符,然后逐个进行处理。

有三种方法:

1. for...in...

for i in "hello world":
         print(i)

2. 列表生成式

[print(i) for i in "hello world"]

这种方式貌似看起来也还是for...in..的方法……^^


3. map函数

map(lambda x:print(x), "hello world")


C语言中字符串遍历有多种方法,以下为你详细介绍: ### 通过下标访问遍历 字符串遍历方式和数组一样,可通过下标进行访问,使用循环对每个内存空间进行访问,以终止标识符为结束条件。示例代码如下: ```c #include <stdio.h> #include <string.h> int main() { char str1[6] = "world"; for (int i = 0; i < strlen(str1); i++) { printf("%c ", str1[i]); } printf("\n"); return 0; } ``` 该代码中,使用`for`循环和`strlen`函数获取字符串长度,通过下标`i`逐个访问字符串中的字符并打印输出[^1]。 ### 遍历字符串数组 #### 直接遍历 ```c #include <stdio.h> int main(void) { int i; char cs[][6] = {"VV", "cat", "2020"}; for (i = 0; i < 3; i++) { printf("cs[%d] = \"%s\"\n", i, cs[i]); } return 0; } ``` 上述代码直接使用`for`循环遍历字符串数组,输出每个字符串元素[^2]。 #### 使用函数遍历字符串数组 ```c #include <stdio.h> void traversal(const char s[][6], int n) { int i; for (i = 0; i < n; i++) { printf("s[%d] = \"%s\"\n", i, s[i]); } } int main(void) { char cs[][6] = {"VV", "cat", "2020"}; traversal(cs, 3); return 0; } ``` 此代码定义了`traversal`函数来遍历字符串数组,在`main`函数中调用该函数完成遍历。需注意,在接收二维数组的形参的声明中,只有第一维的数组元素可以省略,如`void traversal(const char s[][6], int n)`是正确的声明方式,而`void traversal(const char s[][], int n)`是不正确的声明方式[^2]。 #### 使用函数遍历字符串每一个字符 ```c #include <stdio.h> void traversal(const char s[][6], int n) { int i; for(i = 0; i < n; i++) { int j = 0; printf("s[%d] = \"", i); while(s[i][j]) { putchar(s[i][j++]); } puts("\""); } } int main(void) { char cs[][6] = {"VV", "cat", "2020"}; traversal(cs, 3); return 0; } ``` 该代码定义的`traversal`函数使用`while`循环遍历字符串数组中的每个字符并输出,以字符串的终止符`'\0'`作为结束条件[^2]。 ### 指针遍历字符串 ```c #include <stdio.h> int main() { char *str = "hello"; while (*str) { printf("%c ", *str); str++; } printf("\n"); return 0; } ``` 上述代码使用字符指针`str`遍历字符串,通过指针的移动逐个访问字符,当指针指向的字符为`'\0'`时结束遍历。当重新为字符指针初始化一个字符串时,并不是修改原来的字符串,因为原来的字符串数据是不可更改的,而是重新创建了一个字符串,把这个新的字符串的地址赋给指针,建议使用字符指针来存储字符串数据,其优势是长度任意[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值