遍历字符串数组的三种fangfa

本文介绍了C语言中字符串的遍历方法及如何将字符串转换为整型数,包括使用标准库函数atoi和自定义函数实现。同时,探讨了不同情况下的字符串处理技巧。
在这里我们重点介绍遍历字符串的三种方法。

  首先我们来看一道编程题目:

  输入一个字符串,且都是数字,也可以是负数,转化成相应的整型数并输出,若输入字母则停止。

  我们知道,在C语言里有一个函数是“atoi”,它可以把字符串转换成整型数,包含在头文件stdlib.h中。以下是我们使用了这个函数的代码。

  1. #include <stdio.h>  
  2.   
  3. #define MAX_SIZE 1024  
  4.   
  5. int main()  
  6. {  
  7.     char str[MAX_SIZE] = {0};  
  8.       
  9.     int result;  
  10.     int i;  
  11.   
  12.     printf("Please input string : ");  
  13.     gets(str);  
  14.   
  15.     result = atoi(str);  
  16.   
  17.     printf("result = %d\n",result);  
  18.   
  19.     return 0;  
  20. }  
#include <stdio.h>

#define MAX_SIZE 1024

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

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

    result = atoi(str);

    printf("result = %d\n",result);

    return 0;
}

运行结果:

正数:
  1. Please input string : 123456  
  2. result = 123456  
Please input string : 123456
result = 123456


负数:
  1. Please input string : -123456  
  2. result = -123456  
Please input string : -123456
result = -123456

带字母的字符串:
  1. Please input string : 123a456  
  2. result = 123  
Please input string : 123a456
result = 123


  使用“atoi”函数做这道题很简单,那么我们能不能自己写一个函数来实现把字符串转换成整型数的功能呢?下面是我们自己写一个函数来实现把字符串转换成整型数的功能的代码。

  1. #include <stdio.h>  
  2.   
  3. #define MAX_SIZE 1024  
  4.   
  5. int my_atoi(charchar *str)  
  6. {  
  7.     int i = 0;  
  8.     int result = 0;  
  9.     int flag = 1;  
  10.   
  11.     if (*str == '-')  
  12.     {  
  13.         flag = -1;  
  14.         str++;  
  15.     }  
  16.   
  17.     while (*str != '\0')  
  18.     {  
  19.         if (*str >= '0' && *str <= '9')  
  20.         {  
  21.             result = result * 10 + ( *str - '0' );  
  22.         }  
  23.         else  
  24.         {  
  25.             break;  
  26.         }  
  27.   
  28.         str++;  
  29.     }  
  30.   
  31.     return result *flag;  
  32. }  
  33.   
  34. int main()  
  35. {  
  36.     char str[MAX_SIZE] = {0};  
  37.       
  38.     int result;  
  39.     int i;  
  40.   
  41.     printf("Please input string : ");  
  42.     gets(str);  
  43.   
  44.     result = my_atoi(str);  
  45.   
  46.     printf("result = %d\n",result);  
  47.   
  48.     return 0;  
  49. }  
#include <stdio.h>

#define MAX_SIZE 1024

int my_atoi(char *str)
{
    int i = 0;
    int result = 0;
    int flag = 1;

    if (*str == '-')
    {
        flag = -1;
        str++;
    }

    while (*str != '\0')
    {
        if (*str >= '0' && *str <= '9')
        {
            result = result * 10 + ( *str - '0' );
        }
        else
        {
            break;
        }

        str++;
    }

    return result *flag;
}

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

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

    result = my_atoi(str);

    printf("result = %d\n",result);

    return 0;
}

运行结果:

正数:
  1. Please input string : 987654321  
  2. result = 987654321  
Please input string : 987654321
result = 987654321


负数:
  1. Please input string : -123456789  
  2. result = -123456789  
Please input string : -123456789
result = -123456789


带字母:
  1. Please input string : 123456a789  
  2. result = 123456  
Please input string : 123456a789
result = 123456


  我们可以看到,用我们自己编写的函数运行的结果也是正确的。那么我们该怎么样编写这个函数呢?其实这里主要的知识点是字符串的遍历问题。如果我们想把字符串转化成整型数,那么我们需要一个一个地访问字符串里的内容,即字符串遍历。

  首先我们介绍遍历字符串的三种方法:

1. for循环(字符数组)

  1. #include <stdio.h>  
  2. #include <string.h>  
  3.   
  4. #define MAX_SIZE 1024  
  5.   
  6. int main()  
  7. {  
  8.     char src[MAX_SIZE] = {0};  
  9.   
  10.     int i;  
  11.   
  12.     int len;  
  13.   
  14.     printf("Please input string : ");  
  15.     gets(src);  
  16.   
  17.     len = strlen(src);  
  18.   
  19.     printf("string = ");  
  20.   
  21.     for (i = 0; i < len; i++)  
  22.     {  
  23.         printf("%c",src[i]);  
  24.     }  
  25.   
  26.     printf("\n");  
  27.   
  28.     return 0;  
  29. }  
#include <stdio.h>
#include <string.h>

#define MAX_SIZE 1024

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

    int i;

    int len;

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

    len = strlen(src);

    printf("string = ");

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

    printf("\n");

    return 0;
}

运行结果:
  1. Please input string : abcdefg123456     
  2. string = abcdefg123456  
Please input string : abcdefg123456   
string = abcdefg123456

  在这里我们首先利用了strlen函数测量字符数组的长度,然后用for循环遍历字符串,将输入的字符串的内容一个字符一个字符输出。


2. while循环(字符数组)

  1. #include <stdio.h>  
  2. #include <string.h>  
  3.   
  4. #define MAX_SIZE 1024  
  5.   
  6. int main()  
  7. {  
  8.     char src[MAX_SIZE] = {0};  
  9.   
  10.     int i = 0;  
  11.   
  12.     printf("Please input string : ");  
  13.     gets(src);  
  14.   
  15.     printf("string = ");  
  16.   
  17.     while (src[i] != '\0')  
  18.     {  
  19.         printf("%c",src[i]);  
  20.         i++;  
  21.     }  
  22.   
  23.     printf("\n");  
  24.   
  25.     return 0;  
  26. }  
#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;
}

运行结果:
  1. Please input string : congcong123456  
  2. string = congcong123456  
Please input string : congcong123456
string = congcong123456

  由于输入的字符串的长度是未知的,然而我们遍历字符串的时候需要用到循环,我们知道当循环次数未知时,最好使用while语句。


3.while循环(指针)

  1. #include <stdio.h>  
  2. #include <string.h>  
  3.   
  4. #define MAX_SIZE 1024  
  5.   
  6. int main()  
  7. {  
  8.     char src[MAX_SIZE] = {0};  
  9.     charchar *temp = src;  
  10.   
  11.     printf("Please input string : ");  
  12.     gets(src);  
  13.   
  14.     printf("string = ");  
  15.   
  16.     while (*temp != '\0')  
  17.     {  
  18.         printf("%c",*temp);  
  19.         temp++;  
  20.     }  
  21.   
  22.     printf("\n");  
  23.   
  24.     return 0;  
  25. }  
#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;
}

运行结果:
  1. Please input string : congcong123  
  2. string = congcong123  
Please input string : congcong123
string = congcong123

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

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

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

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

  在上述“将字符串转化成整型数”的编程题中,还有一个小知识点,就是如何准确地将正数和负数表示出来。首先我们可以利用一个“flag”,我们将flag初始化为1,符号会出现在我们所输入的字符串的首位,只需要判断这个是不是‘-’,如果是的话,将flag置为-1,最后将结果与flag相乘即可,如果是正数,则不用管,正数乘1还是原数。
### 遍历字符串数组的方法 在不同编程语言中,遍历字符串数组的方式有所不同。以下是几种常见编程语言中遍历字符串数组的具体实现。 #### Java 中遍历字符串数组 Java 提供了多种方式来遍历字符串数组。一种简单而直观的方法是使用增强型 `for` 循环: ```java public class TraverseArray { public static void main(String[] args) { String[] str = new String[]{"hello", "world"}; for (String s : str) { System.out.println(s); } } } ``` 这种方法简洁明了,适用于大多数场景[^2]。 另一种方法是利用传统的 `for` 循环配合索引来访问每一个元素: ```java public class IndexTraverse { public static void main(String[] args) { String[] str = {"apple", "banana", "cherry"}; int length = str.length; for (int i = 0; i < length; ++i){ System.out.println(str[i]); } } } ``` 这种方式提供了更多的灵活性,比如可以在循环体内修改当前处理的元素值。 对于更复杂的操作需求,还可以考虑将数组转化为列表再进行迭代或其他形式的操作。 #### Python 中遍历字符串数组 Python 的语法更加简洁友好,可以直接通过简单的 `for...in` 结构轻松完成遍历工作: ```python str_list = ["hello", "world"] for item in str_list: print(item) ``` 如果需要同时获得元素及其对应的索引位置,则可以借助内置函数 `enumerate()` 来实现这一点: ```python str_list = ['red', 'green', 'blue'] for index, value in enumerate(str_list): print(f'Index {index}: Value is {value}') ``` 此外,在某些情况下可能需要用到 NumPy 库提供的功能来进行高效的数据处理,特别是当涉及到大规模数据集时。不过这通常用于数值计算领域而非单纯的文字串列操作[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值