


What are the application methods of character arrays and strings in C language?
c语言字符数组与字符串应用方法是什么?
c语言字符数组与字符串应用方法:
1、字符数组的定义与初始化
字符数组的初始化,最容易理解的方式就是逐个字符赋给数组中各元素。
char str[10]={ 'I',' ','a','m',' ',‘h','a','p','p','y'};
即把10个字符分别赋给str[0]到str[9]10个元素
如果花括号中提供的字符个数大于数组长度,则按语法错误处理;若小于数组长度,则只将这些字符数组中前面那些元素,其余的元素自动定为空字符(即 '\0' )。
2、字符数组与字符串
在c语言中,将字符串作为字符数组来处理。(c++中不是)
在实际应用中人们关心的是有效字符串的长度而不是字符数组的长度,例如,定义一个字符数组长度为100,而实际有效字符只有40个,为了测定字符串的实际长度,C语言规定了一个“字符串结束标志”,以字符'\0'代表。如果有一个字符串,其中第10个字符为'\0',则此字符串的有效字符为9个。也就是说,在遇到第一个字符'\0'时,表示字符串结束,由它前面的字符组成字符串。
系统对字符串常量也自动加一个'\0'作为结束符。例如"C Program”共有9个字符,但在内存中占10个字节,最后一个字节'\0'是系统自动加上的。(通过sizeof()函数可验证)
有了结束标志'\0'后,字符数组的长度就显得不那么重要了,在程序中往往依靠检测'\0'的位置来判定字符串是否结束,而不是根据数组的长度来决定字符串长度。当然,在定义字符数组时应估计实际字符串长度,保证数组长度始终大于字符串实际长度。(在实际字符串定义中,常常并不指定数组长度,如char str[ ])
说明:'\n'代表ASCII码为0的字符,从ASCII码表中可以查到ASCII码为0的字符不是一个可以显示的字符,而是一个“空操作符”,即它什么也不干。用它来作为字符串结束标志不会产生附加的操作或增加有效字符,只起一个供辨别的标志。
对C语言处理字符串的方法由以上的了解后,再对字符数组初始化的方法补充一种方法——即可以用字符串常量来初始化字符数组:
char str[ ]={"I am happy"}; 可以省略花括号,如下所示
char str[ ]="I am happy";
注意:上述这种字符数组的整体赋值只能在字符数组初始化时使用,不能用于字符数组的赋值,字符数组的赋值只能对其元素一一赋值,下面的赋值方法是错误的
char str[ ]; str="I am happy";
不是用单个字符作为初值,而是用一个字符串(注意:字符串的两端是用双引号“”而不是单引号‘'括起来的)作为初值。显然,这种方法更直观方便。(注意:数组str的长度不是10,而是11,这点请务必记住,因为字符串常量"I am happy"的最后由系统自动加上一个'\0')
因此,上面的初始化与下面的初始化等价
char str[ ]={'I',' ','a','m',' ','h','a','p','p','y','\0'};
而不与下面的等价
char str[ ]={'I',' ','a','m',' ','h','a','p','p','y'};
前者的长度是11,后者的长度是10.
说明:字符数组并不要求它的最后一个字符为'\0',甚至可以不包含'\0',向下面这样写是完全合法的。
char str[5]={'C','h','i','n','a'};
可见,用两种不同方法初始化字符数组后得到的数组长度是不同的。
#include <stdio.h> void main(void) { char c1[]={'I',' ','a','m',' ','h','a','p','p','y'}; char c2[]="I am happy"; int i1=sizeof(c1); int i2=sizeof(c2); printf("%d\n",i1); printf("%d\n",i2); }
结果:10 11
3、字符串的表示形式
在C语言中,可以用两种方法表示和存放字符串:
(1)用字符数组存放一个字符串
char str[ ]="I love China";
(2)用字符指针指向一个字符串
char* str="I love China";
对于第二种表示方法,有人认为str是一个字符串变量,以为定义时把字符串常量"I love China"直接赋给该字符串变量,这是不对的。
C语言对字符串常量是按字符数组处理的,在内存中开辟了一个字符数组用来存放字符串常量,程序在定义字符串指针变量str时只是把字符串首地址(即存放字符串的字符数组的首地址)赋给str。
两种表示方式的字符串输出都用
printf("%s\n",str);
%s表示输出一个字符串,给出字符指针变量名str(对于第一种表示方法,字符数组名即是字符数组的首地址,与第二种中的指针意义是一致的),则系统先输出它所指向的一个字符数据,然后自动使str自动加1,使之指向下一个字符...,如此,直到遇到字符串结束标识符 " \0 "。
4、对使用字符指针变量和字符数组两种方法表示字符串的讨论
Although both character arrays and character pointer variables can be used to store and operate strings, there are differences between them and should not be confused.
4.1. The character array consists of several elements, each element contains one character; the character pointer variable stores the address (the first address of the string/character array), and it is by no means a string placed in In the character pointer variable (it is the first address of the string)
4.2. Assignment method:
You can only assign values to each element of the character array. You cannot assign values to the character array using the following methods
char str[14];
str="I love China";
(But it can be used when initializing the character array, that is, char str[14]= "I love China";)
For character pointer variables, use the following method to assign values:
char* a;
a ="I love China";
Or char* a="I love China";
Both can
4.3. Assign initialization to character pointer variables Value (initialization):
char* a="I love China";
Equivalent to:
char* a;
a="I love China";
And for the initialization of the character array
char str[14]= "I love China";
cannot be equivalent to:
char str[14];
str=" I love China";
(This is not initialization, but assignment, and it is wrong to assign values to arrays like this)
4.4. If a character array is defined, then it has a certain memory address; When defining a character pointer variable, it does not point to a certain character data and can be assigned multiple times.
5. String processing function
5.1
char *strcat(char *str1,const char *2);
char *strcat(char *strDestination,const char *strSource );
Function: The function connects the string str2 to the end of str1 and returns the pointer str1
Note: There is a '\0' at the end of the first two strings to be connected. When connecting, remove the '\0' after string 1, leaving only a '\0' at the end of the new string
5.2
char *strcpy(char *str1,const char *2 );
char *strcpy(char *strDestination,const char *strSource );
Function: Copy the characters in the string strSource to the string strDestination, including the null terminator. The return value is the pointer strDestination.
Note:
1. "Character array 1" must be written in the form of an array name. "String 2" can be a character array name or a string constant
2. When copying, copy it to array 1 together with the ' \0 ' after the string.
3. You cannot use assignment statements to directly assign a string constant or character array to a character array (same as ordinary Variable arrays are the same) and can only be processed with the strcpy function.
4. You can use the strcpy function to copy the first few characters in string 2 to character array 1.
Recommended tutorial: "C Video Tutorial"
The above is the detailed content of What are the application methods of character arrays and strings in C language?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

C language data structure: The data representation of the tree and graph is a hierarchical data structure consisting of nodes. Each node contains a data element and a pointer to its child nodes. The binary tree is a special type of tree. Each node has at most two child nodes. The data represents structTreeNode{intdata;structTreeNode*left;structTreeNode*right;}; Operation creates a tree traversal tree (predecision, in-order, and later order) search tree insertion node deletes node graph is a collection of data structures, where elements are vertices, and they can be connected together through edges with right or unrighted data representing neighbors.

The truth about file operation problems: file opening failed: insufficient permissions, wrong paths, and file occupied. Data writing failed: the buffer is full, the file is not writable, and the disk space is insufficient. Other FAQs: slow file traversal, incorrect text file encoding, and binary file reading errors.

C language multithreading programming guide: Creating threads: Use the pthread_create() function to specify thread ID, properties, and thread functions. Thread synchronization: Prevent data competition through mutexes, semaphores, and conditional variables. Practical case: Use multi-threading to calculate the Fibonacci number, assign tasks to multiple threads and synchronize the results. Troubleshooting: Solve problems such as program crashes, thread stop responses, and performance bottlenecks.

How to output a countdown in C? Answer: Use loop statements. Steps: 1. Define the variable n and store the countdown number to output; 2. Use the while loop to continuously print n until n is less than 1; 3. In the loop body, print out the value of n; 4. At the end of the loop, subtract n by 1 to output the next smaller reciprocal.

Algorithms are the set of instructions to solve problems, and their execution speed and memory usage vary. In programming, many algorithms are based on data search and sorting. This article will introduce several data retrieval and sorting algorithms. Linear search assumes that there is an array [20,500,10,5,100,1,50] and needs to find the number 50. The linear search algorithm checks each element in the array one by one until the target value is found or the complete array is traversed. The algorithm flowchart is as follows: The pseudo-code for linear search is as follows: Check each element: If the target value is found: Return true Return false C language implementation: #include#includeintmain(void){i

The readdir function in the Debian system is a system call used to read directory contents and is often used in C programming. This article will explain how to integrate readdir with other tools to enhance its functionality. Method 1: Combining C language program and pipeline First, write a C program to call the readdir function and output the result: #include#include#include#includeintmain(intargc,char*argv[]){DIR*dir;structdirent*entry;if(argc!=2){

C language functions are reusable code blocks, receive parameters for processing, and return results. It is similar to the Swiss Army Knife, powerful and requires careful use. Functions include elements such as defining formats, parameters, return values, and function bodies. Advanced usage includes function pointers, recursive functions, and callback functions. Common errors are type mismatch and forgetting to declare prototypes. Debugging skills include printing variables and using a debugger. Performance optimization uses inline functions. Function design should follow the principle of single responsibility. Proficiency in C language functions can significantly improve programming efficiency and code quality.

C Language Data Structure: Overview of the Key Role of Data Structure in Artificial Intelligence In the field of artificial intelligence, data structures are crucial to processing large amounts of data. Data structures provide an effective way to organize and manage data, optimize algorithms and improve program efficiency. Common data structures Commonly used data structures in C language include: arrays: a set of consecutively stored data items with the same type. Structure: A data type that organizes different types of data together and gives them a name. Linked List: A linear data structure in which data items are connected together by pointers. Stack: Data structure that follows the last-in first-out (LIFO) principle. Queue: Data structure that follows the first-in first-out (FIFO) principle. Practical case: Adjacent table in graph theory is artificial intelligence
