深度剖析C++string(中)

目录

前言

1.string 类对象的部分修改操作

2.其他函数的部分讲解

结束语


前言

上篇博客我们对C++string的定义和一些函数接口做了讲解学习,接下来我们将继续对C++的函数进行学习。

1.string 类对象的部分修改操作

函数名称功能说明

push_back    在字符串后尾插字符c              append    在字符串后追加一个字符串

operator+= (重点)在字符串后追加字符串     

void string5() {
	string s("Hello World");
	string s1("I love you");
	s.push_back('c');
	cout << s << endl;
	
	s.append(" and you");//字符串添加
	cout << s << endl;
	s1.append(s,6);//添加某字符串第n字符之后到另一字符串
	cout << s1 << endl;
	s1.append(5, 't');//添加n个字符
	cout << s1 << endl;
	s1.append("you", 2);//添加2个字符yo到s1
	cout << s1 << endl;
	string s2("Thanks");//加减字符串和字符
	s2 += " you";
	s2 += '!';
	s2 += s;
	cout << s2 << endl;

}

str c_str(重点)返回C格式字符串   

string str;
str.push_back(' ');   // 在str后插入空格
str.append("hello");  // 在str后追加一个字符"hello"
str += 'w';           // 在str后追加一个字符'b'   
str += "orld";          // 在str后追加一个字符串"it"
cout << str << endl;
cout << str.c_str() << endl;   // 以C语言的方式打印字符串

find + npos(重 点) 从字符串pos位置开始往后找字符c, 返回该字符在字符串中的位置

rfind从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置

void string6() {
	// 获取file的后缀
	string file("string.cpp");
	string s("test.cpp.zip");
	size_t find1 = s.find('.');
	size_t find2 = s.rfind('.');
	cout << find1 << endl;
	cout << find2 << endl;
	size_t pos = file.rfind('.');
	string suffix(file.substr(pos, file.size() - pos));
	cout << suffix << endl;

	// npos是string里面的一个静态成员变量
	// static const size_t npos = -1;
}

 

substr在str中从pos位置开始,截取n个字符,然后将其返回

#include <iostream>
#include <string>
using namespace std;
int main ()
{
  string str="We think in generalities, but we live in details.";
                                    

  string str2 = str.substr (3,5);     // "think",第三个位置后的五个字符

  size_t pos = str.find("live");      // position of "live" in str

  string str3 = str.substr (pos);     // get from "live" to the end

  cout << str2 << ' ' << str3 << '\n';

  return 0;
}

#include <iostream>
#include <string>
using namespace std;
int main ()
{
 string str ("This is an example sentence.");
 cout << str << '\n';
  //删除第10个字符后面8个             
  str.erase (10,8);                        
  cout << str << '\n';
// "This is an sentence."
  str.erase (str.begin()+9);               // 删除指向的字符          ^
  cout << str << '\n';
                                           // "This is a sentence."
  str.erase (str.begin()+5, str.end()-9);  //      
  cout << str << '\n';
                                           // "This sentence."
    string s("hello world");                  // 头删
	s.erase(0, 1);
	cout << s << endl;

	s.erase(s.begin());
	cout << s << endl;

	// 尾删
	s.erase(--s.end());
	cout << s << endl;

	s.erase(s.size()-1, 1);
	cout << s << endl;
  return 0;
}

swap() 函数
- 功能:交换两个字符串的内容。
- 参数:接收两个std::string类型的参数。
- 返回值:无返回值。
`swap()`函数允许交换两个字符串的内容,而不会影响原始字符串。这是一个无返回值的函数,因此不能直接获取交换后的字符串。
 replace() 函数
- 功能:用新的字符串替换字符串中的一个子串。
- 参数:
  - 第一个参数:起始迭代器,指定要替换的子串的起始位置。
  - 第二个参数:结束迭代器,指定要替换的子串的结束位置(不包括结束位置)。
  - 第三个参数:新的字符串,用于替换子串。
  -返回值:返回一个指向替换后的字符串的迭代器。
`replace()`函数允许用一个新的字符串替换字符串中的一个子串。如果新字符串的长度大于或等于旧子串的长度,它会替换整个子串;如果新字符串的长度小于旧子串的长度,它会在旧子串的末尾添加额外的空字符,以保持字符串的长度不变。
 

void string7() {
	/*
	string s1("hello world");
	string s2("I love you");
	string s3("thank you");
	s1.swap(s2);
	cout << s1 << endl;
	s3.replace(0, s3.size(), "Programming");
	cout << "After replace: " << s3 << std::endl;
	*/
	//替换空格为指定字符
	string s("hello              world and today!");
	size_t pos = s.find(" ");
	while (pos != string::npos) {
		s.replace(pos, 1, "%%");
		cout << s << endl;
		pos = s.find(" ", pos + 2);
	}
	cout << s << endl;
	//s.replace(5, 1, "%%");
}
void string8() {
	string s("hello              world and today!");
	string temp;
	temp.reserve(s.size());
	for (auto ch :s) {
		if (ch == ' ')
			temp += "%%";
		else
		temp += ch;
	}
	//cout << temp << endl;
	s. swap(temp);
	cout << s << endl;
}

注意:replace参数的设置有很多种,对应了不同实现功能,可以通过上网查询资料进行学习。

补充了解

 

查询一段字符中的任意一个字符。

void string9() {
	string str("Please, replace the vowels in this sentence by asterisks.");
	/*
	size_t found = str.find_first_not_of("abcdef");
	while (found != string::npos) {
		str[found] = '*';
		found = str.find_first_not_of("abcdef", found + 1);
	}
	cout << str << endl;
	*/
	size_t found = str.find_first_of("abcdef");
	while (found != string::npos) {
		str[found] = '*';
		found = str.find_first_of("abcdef", found + 1);
	}
	cout << str << endl;
}

abcdef都被替换成*

官网的样例:

2.其他函数的部分讲解

#include <iostream>
#include <string>
using namespace std;
int main(){
	string s1("hello");
	string s2("world");
	s1=s1+s2;
	cout<<s1<<endl;
	s1=s1+"and bit";
	cout<<s1<<endl;
	return 0;
}

 输入与输出运算符重载

#include <iostream>
#include <string>
using namespace std;
main ()
{
  string name;

 cout << "Please, enter your name: ";
 cin >> name;
 cout << "Hello, " << name << "!\n";

  return 0;
}

 请注意,istream 提取操作使用空格作为分隔符;因此,此操作只会从流中提取可被视为单词的内容

即当我们输入的数据有空格时,就相当于结束了,不会输出空格后面的了。

 为了克服这种情况,C++引入了getline函数,可以读取空格。

void string11() {
	string s;
	cout << "please enter your name:" << endl;
	getline(cin, s);
	cout << "name:" << s << endl;
	//自己设置终止符
	string s1;
	getline(cin, s1, '#');
	cout << s1 << endl;
}

 

下面是官方的比较运算符的代码

// string comparisons
#include <iostream>
#include <vector>

int main ()
{
  std::string foo = "alpha";
  std::string bar = "beta";

  if (foo==bar) std::cout << "foo and bar are equal\n";
  if (foo!=bar) std::cout << "foo and bar are not equal\n";
  if (foo< bar) std::cout << "foo is less than bar\n";
  if (foo> bar) std::cout << "foo is greater than bar\n";
  if (foo<=bar) std::cout << "foo is less than or equal to bar\n";
  if (foo>=bar) std::cout << "foo is greater than or equal to bar\n";

  return 0;
}

 这个操作符大家可以在官网上进行查询了解,我就偷个懒哈哈!!!

结束语

本节内容就到此结束啦,下节我们将对string类的功能进行底层的模拟实现,最后感谢各位友友的支持!!! 

引用和提供了一些示例代码,用于展示如何使用yin::string的c_str()函数。c_str()函数返回一个指向以null结尾的字符数组的指针,即C风格字符串。引用的示例代码展示了如何使用迭代器访问字符串的每一个字符,并将其打印输出。而引用的示例代码展示了如何使用c_str()函数将字符串转换为C风格字符串,并将其打印输出。 至于你提到的"c string每次置零",在C++,使用C风格字符串时,我们需要手动确保字符串以null结尾。这意味着我们需要在字符串的末尾添加一个null字符('\0'),以表示字符串的结束。如果我们需要将字符串重新置零,我们可以使用C++的字符串类的clear()函数来清空字符串内容。例如,我们可以在引用的示例代码添加s1.clear()来清空s1字符串的内容。 请注意,以上提到的函数和操作均是基于C++string类和标准库。yin::string可能是一个自定义的类,因此具体的实现可能会有所不同。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [【C++深度剖析string类的底层结构及其模拟实现](https://blog.csdn.net/m0_70980326/article/details/130029608)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 101
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值