Table of Contents
1. C 风格字符串
1.1 不调用库函数,实现C风格字符串的常用基本函数
2.string 类类型
2.1 对字符串类的基本操作:
2.2 C 风格的字符串与 string 对象的转换
Home Backend Development C#.Net Tutorial What type is the c/c++ string function and how is it converted? for example

What type is the c/c++ string function and how is it converted? for example

Jul 24, 2018 pm 02:38 PM

字符串函数之间的转换,首先要先了解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;
}
Copy after login

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;;
Copy after login

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

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

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 of this Website
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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
The Continued Relevance of C# .NET: A Look at Current Usage The Continued Relevance of C# .NET: A Look at Current Usage Apr 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# .NET From Web to Desktop: The Versatility of C# .NET Apr 15, 2025 am 12:07 AM

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

C# as a Versatile .NET Language: Applications and Examples C# as a Versatile .NET Language: Applications and Examples Apr 26, 2025 am 12:26 AM

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

Deploying C# .NET Applications to Azure/AWS: A Step-by-Step Guide Deploying C# .NET Applications to Azure/AWS: A Step-by-Step Guide Apr 23, 2025 am 12:06 AM

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# .NET and the Future: Adapting to New Technologies C# .NET and the Future: Adapting to New Technologies Apr 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.

C# and the .NET Runtime: How They Work Together C# and the .NET Runtime: How They Work Together Apr 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# and .NET: Understanding the Relationship Between the Two C# and .NET: Understanding the Relationship Between the Two Apr 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).

C# .NET Development: A Beginner's Guide to Getting Started C# .NET Development: A Beginner's Guide to Getting Started Apr 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.

See all articles