C-函数和字符串
在本教程中,我们将学习如何使用C编程语言在函数中传递和使用字符串。
我们知道,字符串是用双引号引起来的字符序列。
例如," Hello World"是一个字符串,由一系列大写和小写英文字母组成,并且两个单词之间用空格隔开。
因此,共有11个字符。
我们知道,C编程语言中的字符串以NULL\ 0字符结尾。
因此,为了保存上面的字符串,我们需要一个大小为12的数组。
前11个位置将用于存储单词,空格和第12个位置将用于容纳NULL字符以标记结尾。
接受一维字符串的函数声明
我们知道字符串存储在数组中,因此,要将一维数组传递给函数,我们将具有以下声明。
returnType functionName(char str[]);
例:
void displayString(char str[]);
在上面的示例中,我们有一个名为" displayString"的函数,它接受类型为" char"的参数,并且该参数是一维数组,因为我们使用的是[]方括号。
将一维字符串传递给函数
要将一维字符串作为参数传递给函数,我们只需编写字符串数组变量的名称。
在下面的示例中,我们有一个字符串数组变量message,并将其传递给displayString函数。
#include <stdio.h>
void displayString(char []);
int main(void) {
//variables
char
message[] = "Hello World";
//print the string message
displayString(message);
return 0;
}
void displayString(char str[]) {
printf("String: %s\n", str);
}
String: Hello World
我们可以打印字符串的另一种方法是使用" for"或者" while"之类的循环并打印字符,直到我们击中NULL字符为止。
在以下示例中,我们重新定义了displayString函数逻辑。
#include <stdio.h>
void displayString(char []);
int main(void) {
//variables
char
message[] = "Hello World";
//print the string message
displayString(message);
return 0;
}
void displayString(char str[]) {
int i = 0;
printf("String: ");
while (str[i] != '
``` sh
String: Hello World
```') {
printf("%c", str[i]);
i++;
}
printf("\n");
}
returnType functionName(char [][C], type rows);
接受二维字符串的函数声明
为了接受二维字符串数组,函数声明将如下所示。
void displayCities(char str[][50], int rows);
例:
#include <stdio.h>
void displayCities(char [][50], int rows);
int main(void) {
//variables
char
cities[][50] = {
"Bangalore",
"Chennai",
"Kolkata",
"Mumbai",
"New Delhi"
};
int rows = 5;
//print the name of the cities
displayCities(cities, rows);
return 0;
}
void displayCities(char str[][50], int rows) {
//variables
int r, i;
printf("Cities:\n");
for (r = 0; r < rows; r++) {
i = 0;
while(str[r][i] != '
``` sh
Cities:
Bangalore
Chennai
Kolkata
Mumbai
New Delhi
```') {
printf("%c", str[r][i]);
i++;
}
printf("\n");
}
}
在上面的示例中,我们有一个名为" displayCities"的函数,它采用类型为" char"的二维字符串数组。
str是二维数组,因为我们正在使用两个[] []方括号。
重要的是指定数组的第二维,在此示例中,第二维即列总数为50。
第二个参数"行"告诉我们二维二维字符串数组" str"中的总行数。
该函数的返回类型设置为" void",这意味着它将不返回任何值。
将二维字符串传递给函数
要将二维字符串传递给函数,我们只需将字符串数组变量的名称编写为函数参数。
在下面的示例中,我们将5个城市的名称保存在类型为char的cities数组中。
我们将使用displayCities函数来打印名称。

