string

链接:https://zh.cppreference.com/w/cpp/string/basic_string

string 初始化

string c("Exemplary");
string c = "Exemplary";
string c(4,'=');//"===="

 assign方法

int main(){
	string s;
	
	// assign(size_type count, CharT ch)
	s.assign(4,'=');//初始化4个‘=’的字符串
	cout<<s<<'\n';//"====" 
	
	string const c("Exemplary");
	// assign(basic_string const& str)
	s.assign(c);//用字符串初始化字符串
	cout<<s<<'\n';//"Exemplary"
	
	// assign(basic_string const& str, size_type pos, size_type count)
	s.assign(c, 0, c.length()-1);//用选取字符串一定数目的字符初始化字符串
	cout<<s<<'\n';// "Exemplar";
	
	// assign(charT const* s, size_type count)
	s.assign("C-style string", 7);//截取固定长度的字符串初始化字符串
	cout<<s<<'\n';// "C-style"
	
	// assign(basic_string&& str)
	s.assign(string("C++ by") + "example");
	cout<<s<<'\n'; // "C++ by example"
	
	// assign(charT const* s)
	s.assign("C-style\0string");
	cout<<s<<'\n';//"C-style" ,\0表示空字符,用C-style\0string初始化s, 被空字符\0截断
	
	char mutable_c_str[] = "C-style string";
	// assign(InputIt first, InputIt last)
	s.assign(begin(mutable_c_str), end(mutable_c_str)-1);//用迭代器初始化
	cout<<s<<'\n';// "C-style string"
	
	//assign(std::initializer_list<charT> ilist)
	s.assign({'C', '-', 's', 't', 'y', 'l', 'e' });
	cout<<s<<'\n'; // "C-style"
	
	return 0;
}

insert,push_back(), pop_back(),append

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main(){
	string s = "This is an example";
	cout<<s<<'\n';//This is an example
	
	//basic_string& erase( size_type index = 0, size_type count = npos )
	//移除始于 index 的 min(count, size() - index) 个字符。
	s.erase(0, 5);
	cout<<s<<'\n';//is an example
	
	//iterator erase( const_iterator position );
	//算法库的find返回iterator
	s.erase(find(s.begin(), s.end(),' '));
	cout<<s<<'\n';//isan example
	
	//string.find返回查找到的字符索引,找不到返回string::npos
	//从npos清楚
	s.erase(s.find(' '));
	cout<<s<<'\n';//isan
	
	s.push_back('g');
	cout<<s<<'\n';//isang
	
	s.pop_back();
	cout<<s<<'\n';//isan
}

compare

 #include <cassert>
 #include <string>
 #include <iostream>
 int main(){
	{
        int compare_value{
            std::string{"Batman"}.compare(std::string{"Superman"})
        };
        std::cout << (
			//int compare( const basic_string& str ) const;比较string与str
            compare_value < 0 ? "Batman comes before Superman\n" :
            compare_value > 0 ? "Superman comes before Batman\n" :
            "Superman and Batman are the same.\n"
        );
	}	
	{
        int compare_value{
            std::string{"Batman"}.compare(3, 3, std::string{"Superman"})
        };
        std::cout << (
		//int compare( size_type pos1, size_type count1,const basic_string& str ) const;//比较string的[pos1, pos1+count1)的子串与str
            compare_value < 0 ? "man comes before Superman\n" :
            compare_value > 0 ? "Superman comes before man\n" :
            "man and Superman are the same.\n"
        );
    }
	return 0;
}

append

#include <string>
#include <iostream>
using namespace std;

int main(){
	string str = "string";
	const char* cptr = "C-string";
	const char carr[] = "Two and one";
	
	string output;
	output.append(3, '*');//basic_string& append( size_type count, CharT ch ),后附count个ch,“***”
	output.append(str);//basic_string& append( const basic_string& str ),后附string str, ***string
	output.append(str, 3, 3);//basic_string& append( const basic_string& str, size_type pos, size_type count), 后附str的子串[pos, pos+count), ***stringing
	output.append(begin(carr)+3, end(carr));//basic_string& append( InputIt first, InputIt last );后附范围[first, last), ***stringing and one
	output.append({ ' ', 'l', 'i', 's', 't' });//basic_string& append( std::initializer_list<CharT> ilist );后附列表, ***stringing and one list
}

starts_with, ends_with (C++20起),replace(C++14起)

#include <iostream>
#include <string>
using namespace std;
int main(){
	string str = "string";
	char  chs[] = "str";
	str.starts_with("str") == True ? cout<<"True": cout<<"False";//以C++-string开头
	str.starts_with(chs) == True ? cout<<"True": cout<<"False";//以C-string开头
	str.starts_with('s') == True ? cout<<"True": cout<<"False";//以单个字符开头
	
	string str_p("The quick brown fox jumps over the lazy dog");
	//basic_string& replace( size_type pos, size_type count, const basic_string& str );将[pos, pos+count)替换为str
	str_p.replace(10, 5, "red");//"The quick red fox jumps over the lazy dog"
	//basic_string& replace( const_iterator first, const_iterator last, size_type count2, CharT ch );  替换为count2个ch      
	str_p.replace(str_p.begin(), str_p.begin() + 3, 1, 'A');//"A quick red fox jumps over the lazy dog"
	return 0;
}

容量

empty

检查字符串是否为空 
(公开成员函数)

size
length

返回字符数 
(公开成员函数)

max_size

返回字符数的最大值 
(公开成员函数)

reserve

保留存储 
(公开成员函数)

capacity

返回当前对象分配的存储空间能保存的字符数量 
(公开成员函数)

shrink_to_fit

(C++11)

通过释放不使用内存减少内存使用 
//capacity返回字符串当前已为之分配空间的字符数。
#include <iostream>
#include <string>
#include <cassert>
void show_capacity(std::string const& s)
{
    std::cout << "'" << s << "' has capacity " << s.capacity() << ".\n";
}
int main()
{
    std::string s("Exemplar");
    show_capacity(s);
    s += " is an example string.";
    show_capacity(s);
	s.clear();
	assert(s.empty());
	std::cout<<"size = "<<s.size()<<'\n';
	s.shrink_to_fit();
	show_capacity(s);
}
/*
'Exemplar' has capacity 8.
'Exemplar is an example string.' has capacity 30.
'' has capacity 30.
size = 0
'' has capacity 0.
*/

erase 

#include <iostream>
#include <iterator>
#include <string>
using namespace std;

int main(){
	string s("xmplr");
	
	//insert(size_type index, size_type count, char ch)
	s.insert(0, 1, 'E');
	std::cout<<"s = "<<s<<'\n';
	
	//insert(size_type index, char ch)
	s.insert(2,"e");//在索引2的字符前插入1个‘e’
	std::cout<<"s = "<<s<<'\n';
	
	//insert(size_type index, string const& str)
	s.insert(6, "a");
	std::cout<<"s = "<<s<<'\n';
	
	//insert(size_type index, string const& str, size_type index_str, size_type count)
	s.insert(8, " is an example string.", 0, 14);
	std::cout<<"s = "<<s<<'\n';
	
	//insert(const_iterator pos, char ch)
	s.insert(s.begin() + s.find_first_of('n')+1,':');
	std::cout<<"s = "<<s<<'\n';
	
	//insert(const_iterator pos, InputIt first, Input last)
	{
		string seq = "string";//迭代器初始化
		s.insert(s.begin()+s.find_last_of('e') + 1, begin(seq), end(seq));
		std::cout<<"s = "<<s<<'\n';
	}
	
	//insert(const_iterator pos, initializer_list<char>)
	s.insert(s.cbegin() + s.find_first_of('g') + 1, {'.'});
	std::cout<<"s = "<<s<<'\n';
	return 0;
}

 

查找

find

于字符串中寻找字符 
(公开成员函数)

rfind

寻找子串的最后一次出现 
(公开成员函数)

find_first_of

寻找字符的首次出现 
(公开成员函数)

find_first_not_of

寻找字符的首次缺失 
(公开成员函数)

find_last_of

寻找字符的最后一次出现 
(公开成员函数)

find_last_not_of

寻找字符的最后一次缺失 
#include <cmath>
#include <iostream>
#include <string>

using namespace std;

void print(size_t n, string const &s)
{
    if (n == string::npos) {
        cout << "not found\n";
    } else {
        cout << "found: " << s.substr(n) << '\n';
    }
}

int main()
{
    size_t n;
   string const s = "This is a string";
    // 从 string 开始搜索
    n = s.find("is");
    print(n, s);
    // 从位置 5 开始搜索
    n = s.find("is", 5);
    print(n, s);
    // 寻找单个字符
    n = s.find('a');
    print(n, s);
    // 寻找单个字符
    n = s.find('q');
    print(n, s);
}

substr

#include <iostream>
#include <string>
using namespace std;

int main(){
	string a = "0123456789abcdefghij"
	//basic_string substr( size_type pos = 0, [size_type count = npos] ) const  
	string sub1 = a.substr(10);
	cout<< sub1 << '\n';//abcdefghij
	string sub2 = a.substr(5, 3);
	cout<< sub2 <<'\n';//567
	string b = "BBB";
	string c = "CCC";
	b.swap(c);//交换b和c的内容,b = "CCC", c = "BBB"
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值