


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!

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.


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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
