search
HomeBackend DevelopmentC#.Net TutorialSummary of usage of string objects in C++

C Compared with the C language, C has greatly enhanced support for strings. In addition to using C-style strings, you can also use the built-in data type string. The string class is particularly convenient for processing strings because of the function encapsulation. , let’s count the functions of the string class below

First of all, if you want to call the string class, include its header file first#include <string></string>

string s1;//变量s1只是定义但没有初始化,所以其默认值为""即空字符串string s2="Hello World!";//变量s2在定义时同时被初始化/*string类的变量可以相互之间直接赋值,不需要像C语言一样,使用strcpy()函数一个字符一个字符的去赋值*///例如string s3=s2;//此时s3的内容和s2一样也是Hello World!//如果需要定义一个由很多相同字符组成的字符串时,还有另外的简便写法string s4(int n,char c);//s4是被初始化为由n的字符c组成的字符串

About the request In C language, we can use the strlen() function to find the length of a string. In C, we can also use strlen(s3); this method can find the actual length of the s3 string, but because C has a different relationship with the string class Languages ​​are fundamentally different, so we generally call the string.length() function to find the length of a string

int len=0;len=string.length(s3);
cout<<"s3字符串的长度为"<<len<<endl;

As we mentioned above, if a string-like string is assigned to another string-like string, Just assign the value directly, but what if the string class is assigned to the char* class or the char* class is assigned to the string class? Of course, it cannot be assigned directly, just look at the code

//string类赋值给string类string s1="hello world";string s2;
s2=s1;//string类赋值给char*类string s1="hello world";char str[20]={0};
strcpy_s(str,s1.c_str());//char*类赋值给string类char str[20]="hello world";string s2;
s2=str;

At the same time, string type variables can also use character array operations to change one of the variables in it, for example

#include <iostream>#include <string>string s1="this is my house";int i;//如果我们现在想改变里面某一个字符,可以直接将s1当成数组,找到对应的下标来改变i=6;
s[i]=&#39;t&#39;;//这样就可以将第6个字符改成t了

With string class, we can use the " " or " = " operator to directly splice strings, which is very convenient. We no longer need to use strcat(), strcpy(), malloc() and other functions in C language to splice strings. You no longer have to worry about insufficient space and overflow. When using "" to splice strings, both sides of the operator can be string strings, a string string and a C-style string, or a string string and a char character.

Assignment of string class

string &operator=(const string &s);//把字符串s赋给当前字符串 string &assign(const char *s);//用c类型字符串s赋值string &assign(const char *s,int n);//用c字符串s开始的n个字符赋值string &assign(const string &s);//把字符串s赋给当前字符串string &assign(int n,char c);//用n个字符c赋值给当前字符串string &assign(const string &s,int start,int n);//把字符串s中从start开始的n个字符赋给当前字符串string &assign(const_iterator first,const_itertor last);//把first和last迭代器之间的部分赋给字符串

Connection of string

string &operator+=(const string &s);//把字符串s连接到当前字符串的结尾 string &append(const char *s);//把c类型字符串s连接到当前字符串结尾string &append(const char *s,int n);//把c类型字符串s的前n个字符连接到当前字符串结尾string &append(const string &s);    //同operator+=()string &append(const string &s,int pos,int n);//把字符串s中从pos开始的n个字符连接到当前字符串的结尾string &append(int n,char c);        //在当前字符串结尾添加n个字符cstring &append(const_iterator first,const_iterator last);//把迭代器first和last之间的部分连接到当前字符串的结尾

Substring of stringstring substr(int pos = 0,int n = npos) const;/ /Return a string consisting of n characters starting from pos

void swap(string &s2);    //交换当前字符串与s2的值

Search for string

rfind() is very similar to find(), it also searches for sub-characters in a string string, the difference is that the find() function searches backwards from the second parameter, while the rfind() function searches up to the second parameter. If the sub-character has not been found by the subscript specified by the second parameter String, it returns an infinite value 4294967295

int find(char c, int pos = 0) const;//从pos开始查找字符c在当前字符串的位置int find(const char *s, int pos = 0) const;//从pos开始查找字符串s在当前串中的位置int find(const char *s, int pos, int n) const;//从pos开始查找字符串s中前n个字符在当前串中的位置int find(const string &s, int pos = 0) const;//从pos开始查找字符串s在当前串中的位置int rfind(char c, int pos = npos) const;//从pos开始从后向前查找字符c在当前串中的位置int rfind(const char *s, int pos = npos) const;int rfind(const char *s, int pos, int n = npos) const;int rfind(const string &s,int pos = npos) const;//从pos开始从后向前查找字符串s中前n个字符组成的字符串在当前串中的位置,成功返回所在位置,失败时返回string::npos的值

Insertion function of string class:

string &insert(int p0, const char *s);string &insert(int p0, const char *s, int n);string &insert(int p0,const string &s);string &insert(int p0,const string &s, int pos, int n);//前4个函数在p0位置插入字符串s中pos开始的前n个字符string &insert(int p0, int n, char c);//此函数在p0处插入n个字符citerator insert(iterator it, char c);//在it处插入字符c,返回插入后迭代器的位置void insert(iterator it, const_iterator first, const_iterator last);//在it处插入[first,last)之间的字符void insert(iterator it, int n, char c);//在it处插入n个字符c

Regarding the usage of string class objects in C, today I talked about some basics.

Related recommendations:

Summary of usage of string class in standard C

Summary of references in c

The above is the detailed content of Summary of usage of string objects in C++. 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
C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

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.

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 Tools

SecLists

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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.