Cprogramming 简明教程

Array of Strings in C

在 C 编程语言中, string 是以 NULL 结尾的一系列字符序列,它是单维字符数组。而字符串数组是字符串(字符数组)的数组。

In C programming language, a string is an array of character sequences terminated by NULL, it is a one-dimensional array of characters. And, the array of strings is an array of strings (character array).

What is an Array of Strings in C?

因此,可以将字符串数组定义为 -

Thus, an array of strings can be defined as –

为了声明一个字符串,我们使用语句 -

To declare a string, we use the statement −

char string[] = {'H', 'e', 'l', 'l', 'o', '\0'};
Or
char string = "Hello";

Declare and Initialize an Array of Strings

要声明一个字符串数组,你需要声明一个字符类型的 two-dimensional array ,其中第一个下标是字符串的总数,第二个下标是每个字符串的最大大小。

To declare an array of strings, you need to declare a two-dimensional array of character types, where the first subscript is the total number of strings and the second subscript is the maximum size of each string.

要初始化一个字符串数组,你需要在双引号内提供多个字符串,并用逗号分隔。

To initialize an array of strings, you need to provide the multiple strings inside the double quotes separated by the commas.

Syntax

要构造一个字符串数组,使用以下语法 -

To construct an array of strings, the following syntax is used −

char strings [no_of_strings] [max_size_of_each_string];

Example

让我们声明和初始化一个字符串数组来存储 10 种计算机语言的名称,每种语言的最大长度为 15 个字符。

Let us declare and initialize an array of strings to store the names of 10 computer languages, each with the maximum length of 15 characters.

char langs [10][15] = {
   "PYTHON", "JAVASCRIPT", "PHP",
   "NODE JS", "HTML", "KOTLIN", "C++",
   "REACT JS", "RUST", "VBSCRIPT"
};

Printing An Array of Strings

可以使用 printf() function%s 格式说明符打印字符串。要打印字符串数组中的每个字符串,你可以使用 for loop 直到字符串的末尾。

A string can be printed using the printf() function with %s format specifier. To print each string of an array of strings, you can use the for loop till the number of strings.

Example

在下面的示例中,我们声明、初始化并打印了一个字符串数组 -

In the following example, we are declaring, initializing, and printing an array of string −

#include <stdio.h>

int main (){

   char langs [10][15] = {
      "PYTHON", "JAVASCRIPT", "PHP",
      "NODE JS", "HTML", "KOTLIN", "C++",
      "REACT JS", "RUST", "VBSCRIPT"
   };

   for (int i = 0; i < 10; i++){
      printf("%s\n", langs[i]);
   }

   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

PYTHON
JAVASCRIPT
PHP
NODE JS
HTML
KOTLIN
C++
REACT JS
RUST
VBSCRIPT

Note: 每个字符串的大小不等于数组声明中的行大小。\0 符号表示字符串的结束,并且行中剩余的单元格是空的。因此,分配给数组的内存的大部分未被利用,从而造成浪费。

Note: The size of each string is not equal to the row size in the declaration of the array. The "\0" symbol signals the termination of the string and the remaining cells in the row are empty. Thus, a substantial part of the memory allocated to the array is unused and thus wasted.

How an Array of Strings is Stored in Memory?

我们知道,每个 char 类型在内存中占用 1 个字节。因此,将为此数组分配 150 字节的块。虽然此块是连续的内存位置,但 15 个字节的每组构成了一个行。

We know that each char type occupies 1 byte in the memory. Hence, this array will be allocated a block of 150 bytes. Although this block is contagious memory locations, each group of 15 bytes constitutes a row.

假设数组位于内存地址 1000,则该数组的逻辑布局可以显示在下图中 -

Assuming that the array is located at the memory address 1000, the logical layout of this array can be shown as in the following figure −

situated memory address

An Array of Strings with Pointers

为了更有效地使用内存,我们可以使用 pointers 。我们声明一个 1D 的“char *”类型数组,而不是一个 2D 的字符数组。

To use the memory more efficiently, we can use the pointers. Instead of a 2D char array, we declare a 1D array of "char *" type.

char *langs[10] = {
   "PYTHON", "JAVASCRIPT", "PHP",
   "NODE JS", "HTML", "KOTLIN", "C++",
   "REACT JS", "RUST", "VBSCRIPT"
};

在 2D 字符数组中,字符串占据 150 个字节。与此相反,在 array of pointers 中,字符串占据的字节数要少得多,因为每个字符串都随机分配了内存,如下所示 -

In the 2D array of characters, the strings occupied 150 bytes. As against this, in an array of pointers, the strings occupy far less number of bytes, as each string is randomly allocated memory as shown below −

randomly allocated memory

Note: 这里, lang[ ] 是各个字符串的指针数组。

Note: Here, lang[ ] is an array of pointers of individual strings.

array of pointers

Example

我们可以使用 for loop 如下打印字符串数组 -

We can use a for loop as follows to print the array of strings −

#include <stdio.h>

int main(){

   char *langs[10] = {
      "PYTHON", "JAVASCRIPT", "PHP",
      "NODE JS", "HTML", "KOTLIN", "C++",
      "REACT JS", "RUST", "VBSCRIPT"
   };

   for (int i = 0; i < 10; i++)
      printf("%s\n", langs[i]);

   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

PYTHON
JAVASCRIPT
PHP
NODE JS
HTML
KOTLIN
C++
REACT JS
RUST
VBSCRIPT

这里, langs 是指向 10 个字符串数组的指针。因此,如果 langs[0] 指向地址 5000,则 "langs + 1" 将指向存储第二个字符串的指针的地址 5004。

Here, langs is a pointer to an array of 10 strings. Therefore, if langs[0] points to the address 5000, then "langs + 1" will point to the address 5004 which stores the pointer to the second string.

因此,我们还可以使用以下循环变体来打印字符串数组 −

Hence, we can also use the following variation of the loop to print the array of strings −

for(int i = 0; i < 10; i++){
   printf("%s\n", *(langs + i));
}

当字符串在数组中存储时,有很多用例。我们来研究一些用例。

When strings are stored in array, there are a lot use cases. Let study some of the use cases.

Find the String with the Largest Length

在下面的示例中,我们分别将第一个字符串的长度及其位置(为“0”)存储在 variables “l”和“p”中。在 for 循环中,每当找到更大长度的字符串时,我们都会更新这些变量。

In the following example, we store the length of first string and its position (which is "0") in the variables "l" and "p" respectively. Inside the for loop, we update these variables whenever a string of larger length is found.

Example

请看以下示例:

Take a look at the following example −

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

int main (){

   char langs [10][15]  = {
      "PYTHON", "JAVASCRIPT", "PHP",
      "NODE JS", "HTML", "KOTLIN", "C++",
      "REACT JS", "RUST", "VBSCRIPT"
   };

   int l = strlen(langs[0]);
   int p = 0;

   for (int i = 0; i < 10; i++){
      if (strlen(langs[i]) >= l){
         l = strlen(langs[i]);
         p = i;
      }
   }
   printf("Language with the longest name: %s Length: %d", langs[p], l);

   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

Language with longest name: JAVASCRIPT Length: 10

Sort a String Array in Ascending Order

我们需要使用 strcmp() function 来比较两个字符串。如果将字符串比较的值大于 0,则表示第一个参数字符串按字母顺序出现在第二个字符串之后。然后,我们使用 strcmp() 函数交换这两个字符串。

We need to use the strcmp() function to compare two strings. If the value of comparison of strings is greater than 0, it means the first argument string appears later than the second in alphabetical order. We then swap these two strings using the strcmp() function.

Example

请看以下示例:

Take a look at the following example −

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

int main (){

   char langs [10][15] = {
      "PYTHON", "JAVASCRIPT", "PHP",
      "NODE JS", "HTML", "KOTLIN", "C++",
      "REACT JS", "RUST", "VBSCRIPT"
   };

   int i, j;
   char temp[15];
   for (i = 0; i < 9; i++){
      for (j = i + 1; j < 10; j++){
         if (strcmp(langs[i], langs[j]) > 0){
            strcpy(temp, langs[i]);
            strcpy(langs[i], langs[j]);
            strcpy(langs[j], temp);
         }
      }
   }

   for (i = 0; i < 10; i++){
      printf("%s\n", langs[i]);
   }

   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

C++
HTML
JAVASCRIPT
KOTLIN
NODE JS
PHP
PYTHON
REACT JS
RUST
VBSCRIPT

在本章中,我们解释了如何声明字符串数组以及如何使用 string functions 对其进行操作。

In this chapter, we explained how you can declare an array of strings and how you can manipulate it with the help of string functions.