search
HomeBackend DevelopmentC#.Net TutorialWhat type is the c/c++ string function and how is it converted? for example

字符串函数之间的转换,首先要先了解C++字符串的组成,C++提供了两种字符串的表示:C 风格的字符串和标准 C++引入的 string 类类型。

1. C 风格字符串

C 风格的字符串起源于 C 语言 并在 C++中继续得到支持。字符串被存储在一个字符数组中 一般通过一个 char*类型的指针来操纵它 。

标准 C 库为操纵 C 风格的字符串提供了一组函数,例如:

int strlen( const char* ); // 返回字符串的长度

int strcmp( const char*, const char* ); // 比较两个字符串是否相等

char* strcpy(char*, const char* ); // 把第二个字符串拷贝到第一个字符串中

标准 C 库作为标准的 C++的一部分被包含在其中。为使用这些函数,我们必须包含相关的 C 头文件#include

1.1 不调用库函数,实现C风格字符串的常用基本函数

#include<iostream>
#include<cstring>
#include<cassert>
using namespace std;
/*返回字符串长度*/
int MyStrlen(const char * ch)
{
	assert(ch!=NULL);
	int i=0,count=0;
	const char *t=ch;	//用一个临时指针去遍历,防止改变原来指针指向。
	while(t[i]!=&#39;\0&#39;)
	{
		count++;
		i++;
	}
	return count;
}

/*把第二个字符串拷贝到第一个字符串中,返回第一个字符串的首部指针。*/
char* MyStrcpy(char *des,const char *src)
{
	assert((des!=NULL)&&(src!=NULL));
	int i=0;
	char *add=des;	//用add记录des的首部。
	while(src[i]!=&#39;\0&#39;)
	{
		des[i]=src[i];
		i++;
	}
	des[i]=&#39;\0&#39;;
	return add;
}

/*
比较两个字符串是否相等。
相等则返回0,前一个字符串比后一个小则返回-1,否则返回1。
*/
int MyStrcmp(const char *ch1,const char *ch2)
{
	assert((ch1!=NULL)&&(ch2!=NULL));
	int i=0;
	const char *str1=ch1;	//定义两个临时指针。
	const char *str2=ch2;
	while((str1[i]!=&#39;\0&#39;)||(str2[i]!=&#39;\0&#39;))
	{
		if(str1[i]<str2[i])
		{
			return -1;
		}
		else if(str1[i]>str2[i])
		{
			return 1;
		}
		else
		{
			i++;
		}
	}
	return 0;
}
int main()
{
	char ch[]="cavely";
	char ch2[]="julia";
	cout<<MyStrlen(ch)<<endl;	//6
	cout<<MyStrcmp(ch,ch2)<<endl;	//-1
	/*
	下面这两句不能写成:
	char ch3[100];
	ch3=MyStrcpy(ch,ch2);	//数组名是一个地址【常量】。不能被赋值
	*/
	char *ch3;
	ch3=MyStrcpy(ch,ch2);
	cout<<ch3<<endl;	//julia
	return 0;
}

 

2.string 类类型

要使用 string 类型 必须先包含相关的头文件#include

string str("hello");       //①定义一个带初值的字符串

string str2;                 // ②定义空字符串

string str3( str );        //③用一个 string 对象来初始化另一个 string 对象

2.1 对字符串类的基本操作:

(1)str的长度由 size()操作返回(不包含终止空字符),例如str.size()的值为5。

(2)使用 empty()操作判断字符串是否为空,例如:str2.empty()。如果字符串中不含有字符,则 empty()返回布尔常量 true ,否则返回 false。

(3)还可以直接使用赋值操作符 = 拷贝字符串,例如:st2 = st3; // 把 st3 拷贝到 st2 中

(4)可以使用加操作符 + 或看起来有点怪异的复合赋值操作符 += 将两个或多个字符串连接起来。例如,给出两个字符串

string s1( "hello, " );

string s2( "world\n" );

我们可以按如下方式将两个字符串连接起来形成第三个字符串

string s3 = s1 + s2;

如果希望直接将 s2 附加在 s1 后面 那么可使用 += 操作符

s1 += s2;

(5)string 类型支持通过下标操作符访问单个字符,例如,在下面的代码段中,字符串中的所有句号被下划线代替。

string str( "fa.disney.com" );
int size = str.size();
for ( int ix = 0; ix < size; ++ix )
if ( str[ ix ] == &#39;.&#39; )
    str[ ix ] = &#39;_&#39;;

上面代码段的实现可用如下语句替代:

replace( str.begin(), str.end(), &#39;.&#39;, &#39;_&#39; );

replace()是泛型算法中的一个,begin()和 end()操作返回指向 string 开始和结束处的迭代器(iterator) 。迭代器是指针的类抽象 ,由标准库提供。replace()扫描 begin()和 end()之间的字符。每个等于句号的字符,都被替换成下划线。

 

2.2 C 风格的字符串与 string 对象的转换

string 类型能够自动将 C 风格的字符串转换成 string 对象。例如,这使我们可以将一个 C 风格的字符串赋给一个 string 对象。

string s1;

const char *pc = "a character array";

s1 = pc; //OK

但是,反向的转换不能自动执行。对隐式地将 string 对象转换成 C 风格的字符串 string类型没有提供支持。例如下面,试图用 s1 初始化 str 就会在编译时刻失败。

char *str = s1; // 编译时刻类型错误

为实现这种转换,必须显式地调用名为 c_str()的操作。名字 c_str()代表了 string 类型与 C 风格字符串两种表示法之间的关系。字面意思是,给我一个 C 风格的字符串表示——即 指向字符数组起始处的字符指针。为了防止字符数组被程序直接处理, c_str()返回了一个指向常量数组的指针 const char*

所以,正确的初始化应该是:const char *str = s1.c_str(); // OK

相关推荐:

从C/C++迁移到PHP判断字符类型的函数

从C/C++迁移到PHP——判断字符类型的函数_php基础

视频:C++ 手册教程-在线手册教程

C Tutorial | C Manual Tutorial

The above is the detailed content of What type is the c/c++ string function and how is it converted? for example. 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
Developing with C# .NET: A Practical Guide and ExamplesDeveloping with C# .NET: A Practical Guide and ExamplesMay 12, 2025 am 12:16 AM

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

C# .NET: Understanding the Microsoft .NET FrameworkC# .NET: Understanding the Microsoft .NET FrameworkMay 11, 2025 am 12:17 AM

.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.

The Longevity of C# .NET: Reasons for its Enduring PopularityThe Longevity of C# .NET: Reasons for its Enduring PopularityMay 10, 2025 am 12:12 AM

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.

Mastering C# .NET Design Patterns: From Singleton to Dependency InjectionMastering C# .NET Design Patterns: From Singleton to Dependency InjectionMay 09, 2025 am 12:15 AM

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 in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

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.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

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

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

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 C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

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.

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

Video Face Swap

Video Face Swap

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

Hot Article

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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

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.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools