C++ 中的字符串类型
2023-03-02 本文已影响0人
不决书
在C++中没事实际意义上的字符串,只有char类型的字符,字符在C++底层也是通过ASCII编号来记录的,字符串类型其实就是字符数组类型,我们在C语言中的定义方式为:
int main(){
// 定义一个字符串
char* str = "David";
// 在计算机中,认为一个字符数组,最后一位为ASCII的null, 就编码为0,就表示字符串结束
// char* name[5] = {'D', 'a', 'v', 'i', 'd'};
// 正确的方式就是在变量后面再加一个0
char* name[6] = {'D', 'a', 'v', 'i', 'd', '0'};
// 通过索引可以获取到单个字符,获取到字符 v
char a = str[2];
// 输出
std::cout << a << std::endl;
std:cout << str << std:endl;
// 这里输出的结果就是错误的具体看下图
std:cout << name << std:endl;
std::cin.get();
}
char* name[5] = {'D', 'a', 'v', 'i', 'd'} 的输出结果
C++标准库STD提供了字符串类型,基本使用方法为
#include <iostream>
#include <string>
int main(){
// 定义一个字符串
std::string name = "David";
// 这里输出std:string 类型,需要 include <string>
std::cout << name << std::endl;
}
根据前面说讲的内容,因为字符串,其实就是一个数组,所以以下代码会报错
#include <iostream>
#include <string>
int main(){
// 定义一个字符串,这里的字符串相加是不可以的
std::string name = "David" + "Hello";
// 这里输出std:string 类型,需要 include <string>
std::cout << name << std::endl;
}
字符串的相加正常的代码应该是
#include <iostream>
#include <string>
int main(){
// 定义一个字符串,这里的字符串相加是不可以的
std::string name = "David" ;
// 利用标准库提供的操作符重载
name+ = "Hello";
// 或者通过类型强转
std::string name2 = std::string("David") + "hello";
// 这里输出std:string 类型,需要 include <string>
std::cout << name << std::endl;
}
还有一个注意的点,就是在函数中使用字符串作为参数,切记要传地址进去,不然就会copy一份数据,造成空间和性能的浪费,同时要让参数是const 类型,保证数据传入后不被修改,具体代码如下
#include <iostream>
#include <string>
void PrintString(const std::string* str){
std::cout << str << std::endl;
}
int main(){
// 定义一个字符串,这里的字符串相加是不可以的
std::string name = "David" ;
// 利用标准库提供的操作符重载
name+ = "Hello";
PrintString(name);
// 或者通过类型强转
std::string name2 = std::string("David") + "hello";
// 这里输出std:string 类型,需要 include <string>
std::cout << name << std::endl;
}