search
HomeBackend DevelopmentC#.Net TutorialWhat are the application methods of character arrays and strings in C language?

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[]={&#39;I&#39;,&#39; &#39;,&#39;a&#39;,&#39;m&#39;,&#39; &#39;,&#39;h&#39;,&#39;a&#39;,&#39;p&#39;,&#39;p&#39;,&#39;y&#39;};
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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing C# .NET Applications: Unit, Integration, and End-to-End TestingTesting C# .NET Applications: Unit, Integration, and End-to-End TestingApr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewAdvanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewApr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.