C++字符串

前言

当我们在刷题时,对于数组、字符串的题,用C语言的话,有一定的繁琐性,其中的思路不是很难,但是编程过程相当的复杂。而用C++语言的话,要使用字符串,在字符串的加持下,问题解决的更加得心应手,所以整理刷题常用的C++字符串的知识。

string

字符串的定义

#include<string>//或者  <iostream>
using namespace std;//

string a;//定义一个空字符串
string d="";
string b="test string";//定义一个字符串并初始化为test string

字符串常用的函数

字符串赋值

int main() {//字符串直接赋值,前面的直接覆盖
    string a = "aaa";
    string b="bbb";
    cout << a + b <<endl;
    string c = "";
    string d = "dddd";
    a = c;
    b = d;
    cout << a << endl << b << endl;//a=""  b="dddd"
    return 0;
}//

字符串拼接

string str = str1 + str2;// 字符串拼接
string a = "my";
string b = "dog";
string c;
c = a + b;
cout << c;//输出 mydog

字符串的内置方法


str[2];					 // 访问str中的第三个字符,无边界检查,所以推荐使用下一种一种访问方法
str.at(2);				 // 访问str中的第三个字符,有边界检查
str.empty();			 // 判断str是否为空,若 str 为空则返回true,否则返回 false 
str.length()// 获取字符串长度
str.size();         // 获取字符串数量,等价于length()
str.resize(10);      // 表示设置当前string里的串大小,若设置大小大于当前串长度,则用字符\0来填充多余的.
str.resize(10, char c);  // 设置串大小,若设置大小大于当前串长度,则用字符c来填充多余的
str.puch_back('A');    //在str末尾添加一个'A'字符,参数必须是字符形式
str.append("ABC");     //在str末尾添加一个"ABC"字符串,参数必须是字符串形式
str.insert(2, "ABC");   //在str的下标为2的位置,插入"ABC"

字符串与其他类型的转换

字符转化为字符串 char -> string

// char[] -> string,直接赋值即可
char a[] = "dd";
string b = a;
cout << b;//  输出dd

// char* -> string,直接赋值
const char*a = "dd";
string b = a;
cout << b;//  输出dd

字符串转化为字符 string -> char

	// string -> char[],只能通过 strncpy() 拷贝实现
	string a = "I Love u";
	//char c[] = a;	// wrong!!!!
	char c1[] = "this string should longer than str";	// c1长度必须要大于str长度
	strncpy(c1, a.c_str(), a.length() + 1); // 不能漏掉 \0 ,所以要加1
	cout << c1;//  输出 I Love u
	
	// string -> char*,通过类型转换
	string str = "I Love u";
	const char* c = str.c_str(); // 不可修改版,str.c_str()将 string 类型转化为 const char*
	char* c = const_cast<char*>(str.c_str()); // 可修改版  
	cout << c;  //两者输出都是 ;I Love u

字符串转化为整数stoi()

	string c="231";
	int b= stoi(c);
	cout << b;//整数  231

数字转化为字符串to_string()`


	int c=231;
	string b;
	b= to_string(c);
	cout << b;//输出为231 字符串
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值