在 C 语言中创建字符串数组迭代器

CCBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,你将学习如何在 C 编程中创建和遍历字符串数组。你将声明一个字符串数组,使用 while 循环遍历它,处理以 null 结尾的字符串,并打印数组中的每个字符串。这些技能对于处理文本数据和构建更复杂的 C 应用程序至关重要。

本实验涵盖以下步骤:声明字符串数组、使用 while 循环遍历数组、处理以 null 结尾的字符串、打印数组中的每个字符串,以及编译和运行 C 程序。通过完成本实验,你将深入理解如何在 C 中处理字符串数组,这是 C 编程中的一个基本概念。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c(("`C`")) -.-> c/PointersandMemoryGroup(["`Pointers and Memory`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c/ControlFlowGroup -.-> c/while_loop("`While Loop`") c/CompoundTypesGroup -.-> c/arrays("`Arrays`") c/CompoundTypesGroup -.-> c/strings("`Strings`") c/PointersandMemoryGroup -.-> c/pointers("`Pointers`") c/PointersandMemoryGroup -.-> c/memory_address("`Memory Address`") c/FunctionsGroup -.-> c/math_functions("`Math Functions`") c/UserInteractionGroup -.-> c/output("`Output`") subgraph Lab Skills c/while_loop -.-> lab-438245{{"`在 C 语言中创建字符串数组迭代器`"}} c/arrays -.-> lab-438245{{"`在 C 语言中创建字符串数组迭代器`"}} c/strings -.-> lab-438245{{"`在 C 语言中创建字符串数组迭代器`"}} c/pointers -.-> lab-438245{{"`在 C 语言中创建字符串数组迭代器`"}} c/memory_address -.-> lab-438245{{"`在 C 语言中创建字符串数组迭代器`"}} c/math_functions -.-> lab-438245{{"`在 C 语言中创建字符串数组迭代器`"}} c/output -.-> lab-438245{{"`在 C 语言中创建字符串数组迭代器`"}} end

声明字符串数组

在这一步骤中,你将学习如何在 C 编程中声明字符串数组。字符串数组是一种强大的数据结构,允许你在单个变量中存储多个字符串。

  1. 打开 WebIDE,在 ~/project 目录下创建一个名为 string-array.c 的新文件:
cd ~/project
touch string-array.c
  1. 在 WebIDE 中打开该文件,并添加以下代码:
#include <stdio.h>

void main() {
    const char* fruits[] = {
        "Apple",
        "Banana",
        "Cherry",
        "Date",
        NULL
    };
}

这段代码展示了如何在 C 中声明一个字符串数组。让我们分解其中的关键部分:

  • const char* 表示一个常量字符串指针数组
  • fruits[] 是数组的名称
  • 数组中包含四个水果名称作为字符串
  • NULL 用于标记数组的末尾,这在后续的遍历中非常有用

请注意,该数组是以 null 结尾的,这意味着最后一个元素是 NULL。这是 C 中字符串数组的常见做法,因为它有助于在遍历时确定数组的结束位置。

使用 While 循环遍历数组

在这一步骤中,你将学习如何在 C 编程中使用 while 循环遍历字符串数组。基于之前的步骤,我们将修改 string-array.c 文件以打印出水果数组的内容。

  1. 在 WebIDE 中打开 string-array.c 文件:
  2. 更新代码以包含用于遍历数组的 while 循环:
#include <stdio.h>

void main() {
    const char* fruits[] = {
        "Apple",
        "Banana",
        "Cherry",
        "Date",
        NULL
    };

    int i = 0;
    while (fruits[i]) {
        printf("Fruit: %s\n", fruits[i]);
        ++i;
    }
}

让我们分解遍历逻辑:

  • int i = 0 初始化一个索引计数器
  • while (fruits[i]) 继续循环,直到遇到 NULL 终止符
  • printf("Fruit: %s\n", fruits[i]) 打印每个水果名称
  • ++i 递增索引以移动到下一个元素
  1. 编译程序:
gcc string-array.c -o string-array
  1. 运行编译后的程序:
./string-array

示例输出:

Fruit: Apple
Fruit: Banana
Fruit: Cherry
Fruit: Date

while 循环通过检查 NULL 终止符来遍历数组,NULL 终止符标志着数组的结束。这种方法是在 C 中遍历字符串数组的常见且高效的方式。

处理以 Null 结尾的字符串

在这一步骤中,你将学习以 null 结尾的字符串(null-terminated strings)以及它们在 C 编程中如何用于标记字符串数组的末尾。理解 null 终止符对于处理字符串数组至关重要。

  1. 在 WebIDE 中打开 string-array.c 文件:
  2. 修改代码以演示 null 终止符和字符串长度:
#include <stdio.h>
#include <string.h>

void main() {
    const char* fruits[] = {
        "Apple",
        "Banana",
        "Cherry",
        "Date",
        NULL
    };

    int i = 0;
    while (fruits[i]) {
        printf("Fruit: %s\n", fruits[i]);
        printf("Length of %s: %lu\n", fruits[i], strlen(fruits[i]));
        ++i;
    }

    printf("Total number of fruits: %d\n", i);
}

关键修改:

  • 添加 #include <string.h> 以使用 strlen() 函数
  • 使用 strlen() 演示字符串长度
  • 使用循环索引添加水果总数的计数
  1. 编译程序:
gcc string-array.c -o string-array
  1. 运行编译后的程序:
./string-array

示例输出:

Fruit: Apple
Length of Apple: 5
Fruit: Banana
Length of Banana: 6
Fruit: Cherry
Length of Cherry: 6
Fruit: Date
Length of Date: 4
Total number of fruits: 4

理解 null 终止符:

  • 数组末尾的 NULL 充当哨兵值(sentinel value)
  • 它有助于在遍历时确定数组的结束
  • strlen() 通过计数字符直到遇到 null 终止符(\0)来工作
  • 当循环遇到 NULL 指针时停止

打印数组中的每个字符串

在这一步骤中,你将探索从数组中打印字符串的不同方法,包括格式化选项和高级打印技术。

  1. 在 WebIDE 中打开 string-array.c 文件:
  2. 更新代码以演示多种打印技术:
#include <stdio.h>
#include <string.h>

void main() {
    const char* fruits[] = {
        "Apple",
        "Banana",
        "Cherry",
        "Date",
        NULL
    };

    // 方法 1:使用索引的基本打印
    printf("Method 1: Basic Printing\n");
    int i = 0;
    while (fruits[i]) {
        printf("%d: %s\n", i + 1, fruits[i]);
        ++i;
    }

    // 方法 2:带对齐的格式化打印
    printf("\nMethod 2: Formatted Printing\n");
    i = 0;
    while (fruits[i]) {
        printf("| %-10s | Length: %2lu |\n", fruits[i], strlen(fruits[i]));
        ++i;
    }

    // 方法 3:带额外格式化的打印
    printf("\nMethod 3: Advanced Printing\n");
    i = 0;
    while (fruits[i]) {
        printf("Fruit #%d: [%s] has %lu characters\n",
               i + 1, fruits[i], strlen(fruits[i]));
        ++i;
    }
}
  1. 编译程序:
gcc string-array.c -o string-array
  1. 运行编译后的程序:
./string-array

示例输出:

Method 1: Basic Printing
1: Apple
2: Banana
3: Cherry
4: Date

Method 2: Formatted Printing
| Apple      | Length:  5 |
| Banana     | Length:  6 |
| Cherry     | Length:  6 |
| Date       | Length:  4 |

Method 3: Advanced Printing
Fruit #1: [Apple] has 5 characters
Fruit #2: [Banana] has 6 characters
Fruit #3: [Cherry] has 6 characters
Fruit #4: [Date] has 4 characters

演示的打印技术:

  • 使用 printf() 进行基本索引打印
  • 使用宽度和对齐的格式化打印
  • 带额外信息的高级格式化
  • 使用 strlen() 获取字符串长度

总结

在本实验中,你学习了如何在 C 编程中声明字符串数组,这使你能够在单个变量中存储多个字符串。你还学习了如何使用 while 循环遍历数组、处理以 null 结尾的字符串以及打印数组中的每个字符串。这些技术是处理 C 中字符串数据结构的基础,并为更高级的字符串操作任务奠定了坚实的基础。

您可能感兴趣的其他 C 教程