C++自学整理_02
一. 总结:
不论在什么编程语言中,字符串类的数据类型都是一个至关重要的角色,本文将详细讲述在C++编程语言中,字符串类型所具有的特性,以及< string >头文件中所带有的有关字符串的方法函数。
二. 字符串的命名与赋值、什么是 C String
与其他C++语言中的数据类型相同,当你想创建一个字符串类型的变量时,首先需要给一段字符串一个名称,并声明其数据类型。或者当你想生成一个仅可读的字符串的时候,你就可以用到 C String。而如果你想要通过在终端通过 cin 输入一系列字符,从而完成对字符串数据类型的赋值的话,将会遇到一些小问题:
#include <iostream>
#include <string>
using namespace std;
int main(){
// 普通的string
string greeting = "hello";
cout << greeting[0] << endl; // 输出字符串中索引所对应位置的字符
cout << greeting + " world " << endl; // 字符串的拼接组合
greeting += "~"; // 字符串内字符的增加
cout << greeting << endl;
cout << greeting.length() << endl; // 输出字符串的长度
// C string , 这样生成的类似于数组类型的字符串,是不可以进行修改的
char name[] = "demo";
// name = "X"; // 会报错:incompatible types in assignment of 'const char [4]' to 'char [5]'
cout << name << endl;
// 在给 string 赋值的时候会出现的问题
// string test;
// cout << "please enter something for test" << endl;
// cin >> test; // 问题出现在,当你想要输入一个类似于: hello world 的中间有空格隔开的字符串的时候,最终输入的只有空格前边的hello,原因是cin在字符串的输入时会根据空格而认为输入任务的结束
// cout << test << endl;
// 上述问题的解决办法(上述问题还存在单纯的cin而非调用getline(),会让输入的内容带有空格的字符串内容自动赋值给下一个字符串)
string test2;
cout << "please enter something for test2" << endl;
getline(cin, test2);
cout << test2 << endl;
return 0;
}
/*
执行结果
h
hello world
hello~
6
demo
please enter something for test2
2
2
*/
三. 字符串的方法函数
函数名称 | 函数功能 |
---|---|
.length() | 输出字符串的长度 |
.size() | 输出字符串的长度 |
.append() | 在字符串末尾追加字符 |
.insert() | 根据索引位置在字符串内部插入字符 |
.erase() | 根据索引位置以及规定的长度,删除字符串内部的部分字符 |
.pop_back() | 删除字符串末尾的最后一个字符 |
.replace() | 根据索引位置以及规定的长度,替换字符串内部的部分字符 |
.find() | 找到字符串内部的部分字符 |
.substr() | 从原字符串中,根据索引以及规定的长度,提取部分字符 |
代码展示:
#include <iostream>
#include <string>
using namespace std;
int main(){
string method_length = "hello";
string method_size = "hello";
cout << method_length.length() << endl; // .length() 输出字符串长度
cout << method_size.size() << endl; // .size() 输出字符串长度
string method_append = "hello";
cout << method_append.append(" there !") << endl; // .append() 追加字符串内字符
method_append += " my baby !"; // += 追加字符串内字符
cout << method_append << endl;
string method_insert = "hello";
cout << method_insert.insert(1, "~~") << endl; // .insert() 根据索引位置的字符串的插入
string method_erase = "hel lo";
cout << method_erase.erase(3, 3) << endl; // .erase() 根据索引位置以及规定长度的字符串内部字符的删除
cout << method_erase.erase(method_erase.length() - 1) << endl; // 删除字符串末尾的最后一个字符,.length() - 1 的原因是索引是从0开始的,而长度则是从1开始的
method_erase.pop_back(); // .pop_back() 删除字符串末尾的最后一个字符
cout << method_erase << endl;
string method_replace = "hello my baby";
cout << method_replace.replace(9, 12, "son") << endl; // .replace() 替换字符串内的部分内容
string method_find = "hello my baby";
cout << method_find.replace(method_find.find("baby"), 4, "son") << endl; // .find() 找到字符串内部的部分字符;如果找不到的话会返回一串npos数,这个数字的意思就是没有查找到该子字符串
string method_substr = "hello my baby";
cout << method_substr.substr(9, 4) << endl; // .substr() 从总的字符串中,根据索引以及部分字符串的长度,将其提取出来
return 0;
}
/*
执行结果:
5
5
hello there !
hello there ! my baby !
h~~ello
hello
hell
hel
hello my son
hello my son
baby
*/