Cprogramming 简明教程
Character Pointers and Functions in C
What is a Character Pointer in C?
character pointer 存储字符类型或字符数组第一个字符的地址 ( string )。当您需要操作字符串时,字符指针非常有用。
A character pointer stores the address of a character type or address of the first character of a character array (string). Character pointers are very useful when you are working to manipulate the strings.
C 中没有 string 数据类型。“char”类型的数组被视为一个字符串。因此,char 类型数组的指针表示一个字符串。然后,将此 char 指针作为一个 function 的参数传递,以处理字符串。
There is no string data type in C. An array of "char" type is considered as a string. Hence, a pointer of a char type array represents a string. This char pointer can then be passed as an argument to a function for processing the string.
Declaring a Character Pointer
字符指针指向一个字符或一个字符数组。因此,要声明字符指针,请使用以下语法:
A character pointer points to a character or a character array. Thus, to declare a character pointer, use the following syntax:
char *pointer_name;
Initializing a Character Pointer
在声明字符指针之后,您需要使用字符变量的地址对其进行初始化。如果存在字符数组,您可以简单地通过提供字符数组的名称或其第一个元素的地址来初始化字符指针。
After declaring a character pointer, you need to initialize it with the address of a character variable. If there is a character array, you can simply initialize the character pointer by providing the name of the character array or the address of the first elements of it.
Character Pointer Example
In the following example, we have two variables character and character array. We are taking two pointer variables to store the addresses of the character and character array, and then printing the values of the variables using the character pointers.
#include <stdio.h>
int main() {
// Declare two variables
char x = 'P';
char arr[] = "TutorialsPoint";
// Declaring character pointers
char *ptr_x = &x;
char *ptr_arr = arr;
// Printing values
printf("Value of x : %c\n", *ptr_x);
printf("Value of arr: %s\n", ptr_arr);
return 0;
}
Understanding Character Pointer
字符串以下列方式声明为数组:
A string is declared as an array as follows −
char arr[] = "Hello";
字符串是字符的 NULL 终止数组。以上数组中的最后一个元素是 NULL 字符(\0)。
The string is a NULL terminated array of characters. The last element in the above array is a NULL character (\0).
声明 char 类型的指针,并将它的地址指定为第 0 个位置的字符:
Declare a pointer of char type and assign it the address of the character at the 0th position −
char *ptr = &arr[0];
记住,数组本身的名称是第 0 个元素的地址。
Remember that the name of the array itself is the address of 0th element.
char *ptr = arr;
可以使用指针而不是数组变量(没有方括号)来声明字符串。
A string may be declared using a pointer instead of an array variable (no square brackets).
char *ptr = "Hello";
这会导致将字符串存储在内存中,并将其地址存储在 ptr 中。我们可以通过增加 ptr 来遍历字符串。
This causes the string to be stored in the memory, and its address stored in ptr. We can traverse the string by incrementing the ptr.
while(*ptr != '\0'){
printf("%c", *ptr);
ptr++;
}
Accessing Character Array
如果使用 %s 格式说明符打印字符数组,您可以使用字符指针的名称。但是,如果您想访问字符数组的每个字符,您必须在字符指针名称前面使用星号 (*) 然后增加它。
If you print a character array using the %s format specifier, you can do it by using the name of the character pointer. But if you want to access each character of the character array, you have to use an asterisk (*) before the character pointer name and then increment it.
Example
下面是完整的程序代码:
Here is the full program code −
#include <stdio.h>
int main(){
char arr[] = "Character Pointers and Functions in C";
char *ptr = arr;
while(*ptr != '\0'){
printf("%c", *ptr);
ptr++;
}
}
运行代码并检查其输出:
Run the code and check its output −
Character Pointers and Functions in C
Example
或者,使用 %s 格式将 ptr 传递给 printf() 以打印字符串。
Alternatively, pass ptr to printf() with %s format to print the string.
#include <stdio.h>
int main(){
char arr[] = "Character Pointers and Functions in C";
char *ptr = arr;
printf("%s", ptr);
}
运行此代码后,您将获得相同的输出:
On running this code, you will get the same output −
Character Pointers and Functions in C
Character Pointer Functions
"string.h" header 文件定义了许多库函数用于执行字符串处理,例如查找字符串的长度、复制字符串和比较两个字符串。这些函数使用 char 指针参数。
The "string.h" header files defines a number of library functions that perform string processing such as finding the length of a string, copying a string and comparing two strings. These functions use char pointer arguments.
The strlen() Function
strlen() function 返回长度,即字符串中的字符数。strlen() 函数的原型如下:
The strlen() function returns the length, i.e. the number of characters in a string. The prototype of strlen() function is as follows −
int strlen(char *)
以下代码显示了如何打印字符串的长度:
The following code shows how you can print the length of a string −
#include <stdio.h>
#include <string.h>
int main(){
char *ptr = "Hello";
printf("Given string: %s \n", ptr);
printf("Length of the string: %d", strlen(ptr));
return 0;
}
当你运行这段代码时,它将产生以下输出:
When you run this code, it will produce the following output −
Given string: Hello
Length of the string: 5
实际上, strlen() 函数根据用户定义的函数 str_len() 计算字符串长度,如下所示:
Effectively, the strlen() function computes the string length as per the user-defined function str_len() as shown below −
#include <stdio.h>
#include <string.h>
int str_len(char *);
int main(){
char *ptr = "Welcome to Tutorialspoint";
int length = str_len(ptr);
printf("Given string: %s \n", ptr);
printf("Length of the string: %d", length);
return 0;
}
int str_len(char *ptr){
int i = 0;
while(*ptr != '\0'){
i++;
ptr++;
}
return i;
}
当你运行这段代码时,它将产生以下输出:
When you run this code, it will produce the following output −
Given string: Welcome to Tutorialspoint
Length of the string: 25
The strcpy() Function
赋值运算符 ( = ) 不用于将字符串值指定给字符串变量,即 char 指针。相反,我们需要使用具有以下原型的 strcpy() function :
The assignment operator ( = ) is not used to assign a string value to a string variable, i.e., a char pointer. Instead, we need to use the strcpy() function with the following prototype −
char * strcpy(char * dest, char * source);
以下示例说明了如何使用 strcpy() 函数:
The following example shows how you can use the strcpy() function −
#include <stdio.h>
#include <string.h>
int main(){
char *ptr = "How are you doing?";
char *ptr1;
strcpy(ptr1, ptr);
printf("%s", ptr1);
return 0;
}
strcpy() 函数返回指向目标字符串 ptr1 的指针。
The strcpy() function returns the pointer to the destination string ptr1.
How are you doing?
在内部,strcpy() 函数在 user-defined str_cpy() function 中实现以下逻辑:
Internally, the strcpy() function implements the following logic in the user-defined str_cpy() function −
#include <stdio.h>
#include <string.h>
void str_cpy(char *d, char *s);
int main(){
char *ptr = "Using the strcpy() Function";
char *ptr1;
str_cpy(ptr1, ptr);
printf("%s", ptr1);
return 0;
}
void str_cpy(char *d, char *s){
int i;
for(i = 0; s[i] != '\0'; i++)
d[i] = s[i];
d[i] = '\0';
}
当您运行该代码时,它将生成以下输出:
When you runt his code, it will produce the following output −
Using the strcpy() Function
该函数将源字符串中的每个字符复制到目标字符串,直到达到 NULL 字符“\0”。在循环之后,它会在目标数组的末尾添加一个“\0”字符。
The function copies each character from the source string to the destination till the NULL character "\0" is reached. After the loop, it adds a "\0" character at the end of the destination array.
The strcmp() Function
通常的比较运算符(<、>、⇐、>=、== 和 !=)不能用于比较两个字符串。相反,我们需要使用“string.h”头文件中的 strcmp() 函数。此功能的原型如下 −
The usual comparison operators (<, >, ⇐, >=, ==, and !=) are not allowed to be used for comparing two strings. Instead, we need to use strcmp() function from the "string.h" header file. The prototype of this function is as follows −
int strcmp(char *str1, char *str2)
strcmp() function 有 three possible return values −
The strcmp() function has three possible return values −
-
When both strings are found to be identical, it returns "0".
-
When the first not-matching character in str1 has a greater ASCII value than the corresponding character in str2, the function returns a positive integer. It implies that str1 appears after str2 in alphabetical order, as in a dictionary.
-
When the first not-matching character in str1 has a lesser ASCII value than the corresponding character in str2, the function returns a negative integer. It implies that str1 appears before str2 in alphabetical order, as in a dictionary.
以下示例演示如何在 C 程序中使用方法 strcmp() 函数 −
The following example demonstrates how you can use the strcmp() function in a C program −
#include <stdio.h>
#include <string.h>
int main(){
char *s1 = "BASK";
char *s2 = "BALL";
int ret = strcmp(s1, s2);
if (ret == 0)
printf("Both strings are identical\n");
else if (ret > 0)
printf("The first string appears after the second string \n");
else
printf("The first string appears before the second string \n");
return 0;
}
运行代码并检查其输出:
Run the code and check its output −
The first string appears after the second string
将 s1 改变为 BACK 重新运行代码。然后,将获得以下 output −
Change s1 to BACK and run the code again. Now, you will get the following output −
The first string appears before the second string
您可以使用用户自定义函数 str_cmp() 获得类似结果,如下所示 −
You can obtain a similar result using the user-defined function str_cmp(), as shown in the following code −
#include <stdio.h>
#include <string.h>
int str_cmp(char *str1, char *str2);
int main(){
char *s1 = "The Best C Programming Tutorial Available Online";
char *s2 = "The Best C Programming Tutorial Available Online";
int ret = str_cmp(s1, s2);
if (ret == 0)
printf("Both strings are identical\n");
else if (ret > 0)
printf("The first string appears after the second string\n");
else
printf("The first string appears before the second string\n");
return 0;
}
int str_cmp(char *str1, char *str2) {
while (*str1 != '\0' && *str2 != '\0') {
if (*str1 != *str2) {
return *str1 - *str2;
}
str1++;
str2++;
}
// If both strings are equal, return 0
return 0;
}
当你运行这段代码时,它将产生以下输出:
When you run this code, it will produce the following output −
Both strings are identical
str_cmp() 函数比较字符串中同一索引处的字符,直到任一字符串中的字符用尽或字符相等。
The str_cmp() function compares the characters at the same index in a string till the characters in either string are exhausted or the characters are equal.
在同一索引处检测到不相等的字符时,返回它们 ASCII 值的差。当循环终止时返回“0”。
At the time of detecting unequal characters at the same index, the difference in their ASCII values is returned. It returns "0" when the loop is terminated.