C++:string类

标准库中的string

string

1. 字符串是表示字符序列的类
2. 标准的字符串类提供了对此类对象的支持,其接口类似于标准字符容器的接口,但添加了专门用于操作单字节字符字符串的设计特性。
3. string类是使用char(即作为它的字符类型,使用它的默认char_traits和分配器类型(关于模板的更多信 息,请参阅basic_string)
4. string类是basic_string模板类的一个实例,它使用char来实例化basic_string模板类,并用char_traits和allocator作为basic_string的默认参数(根于更多的模板信息请参考basic_string)
5. 注意,这个类独立于所使用的编码来处理字节:如果用来处理多字节或变长字符(UTF-8)的序列,这个类的所有成员(如长度或大小)以及它的迭代器,将仍然按照字节(而不是实际编码的字符)来操作。
总结:
1. string是表示字符串的字符串类
2. 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。
3. string在底层实际是:basic_string模板类的别名,typedef basic_string<char, char_traits, allocator> string;
4. 不能操作多字节或者变长字符的序列。

在使用string类时,必须包含#include<string>头文件以及using namespace std;  

string类的常用接口说明 

string类对象的常见构造

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

int main()
{
	string s0;
	string s1("hello world");
	string s2(s1);
	string s3(s1, 5, 3);
	string s4(s1, 5);
    string s5(10, '#');

	cout << s0 << endl;
	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;
	cout << s4 << endl;
	cout << s5 << endl;
	
    return 0;
}

 string类对象的容量操作

  注意:
1. size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一 致,一般情况下基本都是用size()。
2. clear()只是将string中有效字符清空,不改变底层空间大小。
3. resize(size_t n) 与 resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不同的是当字符个数增多时:resize(n)0来填充多出的元素空间,resize(size_t n, char c)用字符c来填充多出的元素空间。注意:resize在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大 小,如果是将元素个数减少,底层空间总大小不变。
4. reserve(size_t res_arg=0):为string预留空间,不改变有效元素个数,当reserve的参数小于 string的底层空间总大小时,reserver不会改变容量大小。 

size
返回字符串有效字符长度
length
返回字符串有效字符长度
capacity
返回为字符串有效字符开辟空间的大小
max_size最大能开辟的有效字符空间大小
reserve扩容有效字符的空间,可能会大于指定空间
shrink_to_fit缩容空的有效字符空间
resize改变有效字符个数
clear
清空有效字符
empty
检测字符串释放为空串,是返回 true ,否则返回 false
扩容机制 

VS 

g++

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

int main()
{
	string s;
	size_t sz = s.capacity();
	cout << "capacity changed: " << sz << '\n';
	cout << "making s grow:\n";
	for (int i = 0; i < 100; ++i)
	{
		s.push_back('c');
		if (sz != s.capacity())
		{
			sz = s.capacity();
			cout << "capacity changed: " << sz << '\n';
		}
	}
    return 0;
}

 VS

g++

clear

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

int main()
{
	string s1("hello world");
	s1.clear();
	cout << s1 << endl;
	cout << s1.capacity() << endl;
	cout << s1.size() << endl;
    return 0;
}

empty

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

int main()
{
	string s1("hello world");
	cout << s1.empty()<<endl;
	string s2;
	cout << s2.empty() << endl;
    return 0;
}

reserve

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

int main()
{
	string s1("hello worldxxxxxx");
	cout << s1.size() << endl;
	cout << s1.capacity() << endl;

	// 比当前capacity大才会扩容
	s1.reserve(200);
	cout << s1.size() << endl;
	cout << s1.capacity() << endl;
	
    return 0;
}

resize

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

int main()
{
	string s2("hello worldxxxxxx");
	cout << s2.size() << endl;
	cout << s2.capacity() << endl << endl;

	s2.resize(10);

	cout << s2.size() << endl;
	cout << s2.capacity() << endl << endl;

	s2.resize(20);

	cout << s2.size() << endl;
	cout << s2.capacity() << endl << endl;

	s2.resize(100, 'x');

	cout << s2.size() << endl;
	cout << s2.capacity() << endl;
	cout << s2<<endl;
	
    return 0;
}

shrink_to_fit

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

int main()
{
	    string s1;
		s1.shrink_to_fit();
		cout << s1.capacity() << endl;
		cout << s1.size() << endl;
        return 0;
}

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

int main()
{
	string s1("hello world");

	cout << s1.max_size() << endl;
	
	return 0;
}

string类对象的访问及遍历操作

 operator[ ]的使用

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

int main()
{
	string s1("hello world");

	// 下标+[]
	for (size_t i = 0; i < s1.size(); i++)
	{
		cout << s1[i];
		//cout << s1.operator[](i);
	}
	cout << endl;
    //cout<<s1;
    return 0;
}


  迭代器行为像指针一样的类型对象

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

int main()
{
	string s1("hello world");
	string::iterator it1 = s1.begin();
	while (it1 != s1.end())
	{
		cout << *it1;
		it1++;
	}
	cout << endl;
	   
    string::reverse_iterator rit = s1.rbegin();
	while (rit != s1.rend())
	{
		cout << *rit;
		++rit;
	}
	cout << endl;

    return 0;
}

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

int main()
{
	 string s1("hello world");
	string::const_iterator it1 = s1.begin();
	while (it1 != s1.end())
	{
		cout << *it1;
		++it1;
	}
	cout << endl;

	string::const_reverse_iterator rit1 = s1.rbegin();
	while (rit1 != s1.rend())
	{
		cout << *rit1;
		++rit1;
	}
	cout << endl;

    return 0;
}

 加const_代表只读,无法修改


 范围for底层就是迭代器 

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

int main()
{
	string s1("hello world");
	   
	for (auto e : s1)
	{
		cout << e;
	}
	cout << endl;

    return 0;
}

#include<iostream>
using namespace std;
int main()
{
        string s1("hello world");

		for (auto ch : s1)
		{
			cout << ch << " ";
		}
		cout << endl;

		string::iterator it1 = s1.begin();
		while (it1 != s1.end())
		{
			cout << *it1 << " ";
			++it1;
		}
		cout << endl;

        return 0;
}

底层类似是这样的代码,迭代器是通用的,在各容器都存在独自的迭代器且都可以用

string类对象的修改操作

push_back

字符串之后插入一个字符 

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

int main()
{
	string s1("xhello world");
	s1.push_back('!');
	cout << s1 << endl;//xhello world!

    return 0;
}

append 

  • 在str字符串的末尾添加字符串
    string& append (const string& str);
    string& append (const char* s);
    #include<string>
    #include <iostream>
    using namespace std;
    
    int main()
    {
    	string s1="a";
    
    	s1.append("hello bit");
    	cout << s1 << endl; //ahello bit
    
    	
    	string s2("apple");
    	s1.append(s2);
    	cout << s1 << endl; //ahello bitapple
    	
        return 0;
    }
  • 在字符串的的末尾添加str字符串中索引为[subpos, subpos+sublen]的子串
    string& append (const string& str, size_t subpos, size_t sublen = npos);
    #include<string>
    #include <iostream>
    using namespace std;
    
    int main()
    {
    	string str4;
    	string str5 = "six-six-six";
    	
    	cout << str4.append(str5, 4, 4) << endl; //six-
    	cout << str4.append(str5, 4) << endl;    //six-six-six
    
    	return 0;
    }
  • 在字符串str后面添加char字符串的前n个字符
    string& append (const char* s, size_t n);
    #include<string>
    #include <iostream>
    using namespace std;
    
    int main()
    {
    	string str1;
    	const char* chs1 = "h-e-l-l-o";
    	cout << str1.append(chs1, 1) << endl;//h
    	return 0;
    }
    
  • 在字符串str的末尾添加n个字符c
    string& append (size_t n, char c);
    #include<string>
    #include <iostream>
    using namespace std;
    
    int main()
    {
    	string s1 = "a";
    
    
    	s1.append(10, 'x');
    	cout << s1 << endl;//axxxxxxxxxx
    	
        return 0;
    }
  • 在字符串的的末尾添加str字符串中索引为[begin, end)的子串
    template <class InputIterator>   
    string& append (InputIterator first, InputIterator last);
    #include<string>
    #include <iostream>
    using namespace std;
    
    int main()
    {
    	string s1;
    	string s2(" apple ");
    	
    	s1.append(++s2.begin(), --s2.end());//apple
    	cout << s1 << endl;
    	return 0;
    }

operator+=

在字符串后追加一个字符串  

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

int main()
{
	string s3("hello world");
    string s2(" ");
	s3 += s2;
	s3 += "iphone";
	s3 += '6';
	cout << s3 << endl;//hello world iphone6

	return 0;
}

c_str

返回C格式字符串

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

int main()
{
	string s1("hello world");
	string filename("test.cpp");

	FILE* fout = fopen(filename.c_str(), "r");
	return 0;

}

find

找出字母在字符串中的位置

pos:字符串中的某个位置,表示从从这个位置开始的字符串中找指定元素(不填第二个参数,默认从字符串的开头进行查找)

返回值为目标字符的位置(第一个字符位置为0),当没有找到目标字符时返回npos

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

int main()
{
	//找到目标字符的位置
	string s = "hello world!";
    string s1("e");

	cout << s.find(s1) << endl;//1
	cout << s.find("hello", 0) << endl;//0
	cout << s.find("world", 0, 3) << endl;//6 找"world"中前3个有效字符,从0开始找
	cout << s.find('w', 0) << endl;//6

	return 0;
}

find_first_of 

size_t find_first_of ( const string& str, size_t pos = 0 ) const;
size_t find_first_of ( const char* s, size_t pos, size_t n ) const;
size_t find_first_of ( const char* s, size_t pos = 0 ) const;
size_t find_first_of ( char c, size_t pos = 0 ) const;

find_first_of 函数最容易出错的地方是和find函数搞混。它最大的区别就是如果在一个字符串str1中查找另一个字符串str2,如果str1中含有str2中的任何字符,则就会查找成功,而find则不同;

string str1("I am change");

string  str2("about");

int k=str1.find_first_of(str2);    //k返回的值是about这5个字符中任何一个首次在str1中出现的位置;

find_first_not_of

1.返回在字符串中首次出现的不匹配str任何字符的首字符索引, 从pos开始搜索, 如果全部匹配则返回string::npos。   

2.从pox开始起搜索当前字符串, 查找其中与str前n个字符中的任意一个都不匹配的序列, 返回满足条件的第一个字符索引, 否则返回string::npos。   

3.返回在当前字符串中第一个不匹配c字符的索引, 从ps开始搜索, 没用收获则返回string::npos。

std::size_t found = str.find_first_not_of("aeiou");
	while (found != std::string::npos)
	{
		str[found] = '*';
		found = str.find_first_not_of("aeiou", found + 1);
	}
	cout << str << endl;

其他

assign

string &assign(const char *s);用字符串s赋值
string &assign(const char *s,size_t n);用字符串s开始的n个字符赋值
string &assign(const string &str);把字符串s赋给当前字符串
string &assign(size_t n,char c);用n个字符c赋值给当前字符串
string &assign(const string &str,size_t subpos,size_t sublen=npos);

把字符串str中从subpos开始的sublen个字符赋给当前字符串
string &assign(InputIterator first, InputIterator last);

把first和last迭代器之间的部分赋给字符串

[first,last),左闭右开

insert

(1)string &insert(size_t pos, const char* s)
功能:在原字符串下标为pos的字符前插入字符串s
返回值:插入字符串后的结果

(2)string &insert(size_t pos, const char* s, size_t n);
功能:在pos位置插入字符串s的前n个字符
返回值:插入字符串后的结果

(3)string &insert(size_t pos, const string& str);
功能:在pos位置插入字符串str
返回值:插入字符串后的结果
(4)string &insert(size_t pos, const string& str, size_t subpos, size_t sublen = npos);
功能:在pos位置插入字符串str从subpos开始的连续sublen个字符
返回值:插入字符串后的结果

(5)string &insert(size_t pos, size_t n, char c);
功能:在pos处插入n个字符c
返回值:插入字符串后的结果
(6)void insert(const_iterator p, size_t n, char c);
功能:在p处插入n个字符c

(7)iterator insert(const_iterator p, char c)
功能:在p处插入字符c
返回值:插入字符的位置

(8)void insert(iterator p, InputIterator first, InputIterator last);
功能:在p处插入从first开始至last-1的所有字符

[first,last),左闭右开

	//string &insert(int p0,const string &s);
    //在p0位置插入字符串s
    //返回值:插入字符串后的结果
	str1="Working people Working soul Working people are Exalted";
    string str4="I am ";
    str=str1.insert(0,str4);
    cout<<"str1: "<<str1<<endl;             //str1: I am Working people Working soul Working people are Exalted
    cout<<"str: "<<str<<endl;               //str: I am Working people Working soul Working people are Exalted

    //string &insert(int p0,const string &s, int pos, int n);
    //在p0位置插入字符串s从pos开始的连续n个字符
    //返回值:插入字符串后的结果
    str1="Hello ";
    str2="World";
    str=str1.insert(6,str2,0,5);
    cout<<"str1: "<<str1<<endl;             //str1: Hello World
    cout<<"str: "<<str<<endl;               //str: Hello World
	//string &insert(int p0, int n, char c);
    //在p0处插入n个字符c
    //返回值:插入字符串后的结果
    str1="Hello ";
    str=str1.insert(6,5,'y');
    cout<<"str1: "<<str1<<endl;          //str1: Hello yyyyy
    cout<<"str: "<<str<<endl;            //str:Hello yyyyy

    //void insert(iterator it, int n, char c);
    //在it处插入n个字符c
    str1="Hello ";
    str1.insert(str1.end(),5,'y');
    cout<<"str1: "<<str1<<endl;          //str1: Hello yyyyy

    //iterator insert(iterator it, char c)
    //在it处插入字符c
    //返回值:插入字符的位置
    str1="ello ";
    string::iterator it=str1.insert(str1.begin(),'H');
    cout<<"str: "<<str1<<endl;           //str:Hello
    cout<<"*it: "<<*it<<endl;            //*it: H
	//void insert(iterator it, const_iterator first, const_iterator last);
    //在it处插入从first开始至last-1的所有字符
    str1="Hello ";
    str2="World";
    str1.insert(str1.end(),str2.begin(),str2.end());
    cout<<"str1: "<<str1<<endl;          //str1: Hello World

erase

iterator erase (iterator first, iterator last);用于删除指定范围字符串

string& erase(size_t pos=0, size_t len = npos);用于删除指定长度字符串

iterator erase (iterator first, iterator last);用于删除指定范围字符串

[first,last),左闭右开

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

int main()
{
	std::string str("This is an example sentence.");

	str.erase(10, 8);
	cout << str << endl;//This is an sentence.

	str.erase(str.begin() + 9);
	cout << str << endl;//This is a sentence.

	str.erase(str.begin() + 5, str.end()-9);
	cout << str << endl;//This sentence.
	
	return 0;
}

replace

1.应用一:string &replace(size_t pos,size_t len,const &str)被替换位置(pos往后len个字符)
2.应用二:string &replace(size_t pos,size_tlen,const string &str,size_t subpos,size_t sublen)被替换位置(pos往后len长度),替换位置(subpos往后sublen长度)
3.应用三:string &replace(size_t pos,size_t len,const char* s) 插入C串
4.应用四:string &replace(size_t pos,size_t len,const char* cch,size_t n)插入C串前n个字符
5.应用五:string &replace(size_t pos,size_t len,size_t n,char c)在指定位置插入指定个c字符
6.应用六~应用九:(往后为迭代器操作)
string &replace(const_iterator it1,const_iterator it2,const string&str)
string &replace(const_iterator it1,const_iterator it2,const char* cch)
string &replace(const_iterator it1,const_iterator it2,const char* cch,size_t n)
string &replace(const_iterator it1,const_iterator it2,size_t n,char c)

#include<iostream>
#include<string>
using namespace std;
int main() {
	{//应用一:string &replace(size_t pos,size_t len,const &str)实现
		string s = "0123456";
		string str = "ABCD";
		s.replace(2, 2, str);//在s的pos=2位置往后len=2字符(“23”)替换为"ABCD"
		cout << s << "\n"; 
	}
	{//应用二:string &replace(size_t pos, size_tlen, const string &str, size_t subpos, size_t sublen)
		//被替换位置(pos往后len长度),替换位置(subpos往后sublen长度)
		string s = "0123456";
		string str = "ABCD";
		s.replace(2, 2, str, 1, 2);//s在s的pos=2位置往后len=2个字符(“23”)替换为“BC”(str中subpos=1往后两个位置)
		cout << s << "\n";
		
	} 
	{//应用三:string &replace(size_t pos,size_t len,const char* s)  插入C串
		string s = "0123456";
		char str[] = "ABCD";
		s.replace(2, 2, str, 1, 2);s在s的pos=2位置往后len=2个字符(“23”)替换为“BC”(str中subpos=1往后两个位置)
		cout << s << "\n";

	}
	{//应用四:string &replace(size_t pos,size_t len,const char* cch,size_t n)插入C串前n个字符
		string s = "0123456";
		s.replace(2, 2, "ABCD", 2);//在指定位置(pos=2,len=2)插入“ABCD”前两个字符
		cout << s << "\n";
	}
	
	{//应用五:string &replace(size_t pos, size_t len, size_t n, char c)
		string s = "0123456";
		s.replace(2, 2, 5, 'A');//在指定位置(pos=2,len=2)插入5个'A';
		cout << s << "\n";

	}
	{//应用六:(只举一例,其他与size_t操作类似)
		//string &replace(const_iterator first,const_iterator last,const string&str)
		//string &replace(const_iterator first,const_iterator last,const char* cch)
		//string &replace(const_iterator first,const_iterator last,const char* cch,size_t n)
		//string &replace(const_iterator first,const_iterator last,size_t n,char c)
		//需要注意的是迭代器操作中第二个参数不再是len而是位置
		string s = "0123456";
		string str = "ABCD";  
		string::iterator it= s.begin();
		s.replace(it, it+2, str);//s在s的pos=2位置往后len=2个字符(“23”)替换为“BC”(str中subpos=1往后两个位置)
		cout << s << "\n";
	}

	system("pause");
	return 0;
}

substr

截取位置(默认从0开始)[pos,len]的字符串

#include<string>
#include<iostream>
using namespace std;
int main()
{
    string x="Hello_World";
    /*默认截取从0到npos.重载原型为string substr(_off=0,_count=npos);npos一般表示为string类中不存在的位置,_off表示字符串的开始位置,_count截取的字符的数目*/
    cout<<x.substr()<<endl;
    cout<<x.substr(5)<<endl;//截取x[5]到结尾,即npos.重载原型为string substr(_off,_count=npos)
    cout<<x.substr(0,5)<<endl;//以x[0]为始,向后截取5位(包含x[0]),重载原型string substr(_off,_count)
    /*
    备注:
    指定的截取长度加起始位置即_off+_count>源字符串的长度,则子字符串将延续到源字符串的结尾
    */
}

reverse(算法函数)

头文件<algorithm>

void reverse(s.begin(),s.end());

将容器[first,last)范围内的元素颠倒顺序放置

s.begin()对应字符串首元素

s.end()对应字符串‘/0’ 

原地翻转字符串

string类非成员函数

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

int main()
{
	string ss1 = "xxx";
	string ss2 = "yyy";

	string ret = ss1 + ss2;
	cout << ret << endl;//xxxyyy
	
	string ret1 = ss1 + "yyyy";
	string ret2 = "yyyy" + ss2;

	cout << ret1 << endl;//xxxyyyy
	cout << ret2 << endl;//yyyyyyy
	
	return 0;
}

operator<<和operator>>
istream& operator<< (istream& is, string& str);
istream& operator>> (istream& is, string& str);
#include<string>
#include <iostream>
using namespace std;

int main()
{
	string ss1;
	cin >> ss1;
	//operator>>(cin, ss1);

	cout << ss1 << endl;
    //operator<<(cout,ss1)<<endl;

	return 0;

	return 0;
}

getline

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

int main()
{
	string ss1;
	getline(cin,ss1);
	cout << ss1 << endl;

	return 0;
}

相比cin,getline能输入空格字符

relational operators
bool operator== (const string& lhs, const string& rhs) noexcept;
bool operator== (const char*   lhs, const string& rhs);
bool operator== (const string& lhs, const char*   rhs);

bool operator!= (const string& lhs, const string& rhs) noexcept;
bool operator!= (const char*   lhs, const string& rhs);
bool operator!= (const string& lhs, const char*   rhs);

bool operator<  (const string& lhs, const string& rhs) noexcept;
bool operator<  (const char*   lhs, const string& rhs);
bool operator<  (const string& lhs, const char*   rhs);

bool operator<= (const string& lhs, const string& rhs) noexcept;
bool operator<= (const char*   lhs, const string& rhs);
bool operator<= (const string& lhs, const char*   rhs);

bool operator>  (const string& lhs, const string& rhs) noexcept;
bool operator>  (const char*   lhs, const string& rhs);
bool operator>  (const string& lhs, const char*   rhs);

bool operator>= (const string& lhs, const string& rhs) noexcept;
bool operator>= (const char*   lhs, const string& rhs);
bool operator>= (const string& lhs, const char*   rhs);

比大小是逐一比较,相同则往下继续比,遇见不同的则比较ascll码,然后返回1或0的结果

其他

 to_string

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);string to_string (double val);
string to_string (long double val);

将各种类型可以直接转换为字符串类型 

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

int main()
{
	int i = 1234;
	double d = 11.22;
	string s1 = to_string(i);
	string s2 = to_string(d);

	cout << s1 << endl;//1234
	cout << d << endl;//11.22

	return 0;
}

stod

double stod (const string&  str, size_t* idx = 0);
double stod (const wstring& str, size_t* idx = 0);

将double类型转换为字符串类型

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

int main()
{
	string s3("45.55");
	double d3 = stod(s3);

	cout << d3 << endl;//45.55

	return 0;
}

string类的模拟实现

#include<iostream>
using namespace std;
#include<assert.h>
namespace bit
{
	class string
	{
	public:
		typedef char* iterator;
		typedef const char* const_iterator;

		const_iterator begin() const
		{
			return _str;
		}

		const_iterator end() const
		{
			return _str + _size;
		}

		iterator begin()
		{
			return _str;
		}

		iterator end()
		{
			return _str + _size;
		}

		/*	string()
				:_str(new char[1])
				,_size(0)
				,_capacity(0)
			{
				_str[0] = '\0';
			}

			string(const char* str)
				:_size(strlen(str))
				,_str(new char[strlen(str)+1])
				,_capacity(strlen(str))
			{
				strcpy(_str, str);
			}*/

		const char* c_str() const
		{
			return _str;
		}


		string(const char* str = "")
			:_size(strlen(str))
		{
			_capacity = _size;
			_str = new char[_capacity + 1];
			strcpy(_str, str);
		}

		// s2(s1)
		/*string(const string& s)
		{
			_str = new char[s._capacity + 1];
			strcpy(_str, s._str);
			_size = s._size;
			_capacity = s._capacity;
		}
		*/

		// s2(s1)
		string(const string& s)
		{
			string tmp(s._str);
			swap(tmp);
		}

		string& operator=(string tmp)
		{
			// 现代写法
			swap(tmp);

			return *this;
		}

		// s1 = s3;
		/*string& operator=(const string& s)
		{
			char* tmp = new char[s._capacity + 1];
			strcpy(tmp, s._str);

			delete[] _str;
			_str = tmp;
			_size = s._size;
			_capacity = s._capacity;

			return *this;
		}
		*/

		~string()
		{
			delete[] _str;
			_str = nullptr;
			_size = _capacity = 0;
		}

		// 遍历
		size_t size() const
		{
			return _size;
		}

		size_t capacity() const
		{
			return _capacity;
		}

		char& operator[](size_t pos)
		{
			assert(pos < _size);

			return _str[pos];
		}

		const char& operator[](size_t pos) const
		{
			assert(pos < _size);

			return _str[pos];
		}

		void resize(size_t n, char ch = '\0')
		{
			if (n <= _size)
			{
				_str[n] = '\0';
				_size = n;
			}
			else
			{
				reserve(n);
				for (size_t i = _size; i < n; i++)
				{
					_str[i] = ch;
				}
				_str[n] = '\0';
				_size = n;
			}
		}

		void reserve(size_t n)
		{
			if (n > _capacity)
			{
				char* tmp = new char[n + 1];
				strcpy(tmp, _str);
				delete[] _str;
				_str = tmp;

				_capacity = n;
			}
		}

		void push_back(char ch)
		{
			// 扩容2倍
			/*if (_size == _capacity)
			{
				reserve(_capacity == 0 ? 4 : 2 * _capacity);
			}

			_str[_size] = ch;
			++_size;
			_str[_size] = '\0';*/
			insert(_size, ch);
		}

		void append(const char* str)
		{
			// 扩容
			/*size_t len = strlen(str);
			if (_size + len > _capacity)
			{
				reserve(_size + len);
			}

			strcpy(_str + _size, str);
			_size += len;*/
			insert(_size, str);
		}

		string& operator+=(char ch)
		{
			push_back(ch);
			return *this;
		}

		string& operator+=(const char* str)
		{
			append(str);
			return *this;
		}

		void insert(size_t pos, char ch)
		{
			assert(pos <= _size);

			// 扩容2倍
			if (_size == _capacity)
			{
				reserve(_capacity == 0 ? 4 : 2 * _capacity);
			}

			/*int end = _size;
			while (end >= (int)pos)
			{
				_str[end + 1] = _str[end];
				--end;
			}*/

			size_t end = _size + 1;
			while (end > pos)
			{
				_str[end] = _str[end - 1];
				--end;
			}

			_str[pos] = ch;
			++_size;
		}

		void insert(size_t pos, const char* str)
		{
			assert(pos <= _size);
			size_t len = strlen(str);
			if (_size + len > _capacity)
			{
				// 扩容
				reserve(_size + len);
			}

			size_t end = _size + len;
			while (end > pos + len - 1)
			{
				_str[end] = _str[end - len];
				end--;
			}

			strncpy(_str + pos, str, len);
			_size += len;
		}

		void erase(size_t pos, size_t len = npos)
		{
			assert(pos < _size);

			if (len == npos || len >= _size - pos)
			{
				_str[pos] = '\0';
				_size = pos;
			}
			else
			{
				strcpy(_str + pos, _str + pos + len);
				_size -= len;
			}
		}

		void swap(string& s)
		{
			std::swap(_str, s._str);
			std::swap(_size, s._size);
			std::swap(_capacity, s._capacity);
		}

		size_t find(char ch, size_t pos = 0) const
		{
			assert(pos < _size);

			for (size_t i = pos; i < _size; i++)
			{
				if (_str[i] == ch)
					return i;
			}

			return npos;
		}

		size_t find(const char* sub, size_t pos = 0) const
		{
			assert(pos < _size);

			const char* p = strstr(_str + pos, sub);
			if (p)
			{
				return p - _str;
			}
			else
			{
				return npos;
			}
		}

		string substr(size_t pos = 0, size_t len = npos)
		{
			string sub;
			//if (len == npos || len >= _size-pos)
			if (len >= _size - pos)
			{
				for (size_t i = pos; i < _size; i++)
				{
					sub += _str[i];
				}
			}
			else
			{
				for (size_t i = pos; i < pos + len; i++)
				{
					sub += _str[i];
				}
			}

			return sub;
		}

		void clear()
		{
			_size = 0;
			_str[_size] = '\0';
		}

	private:
		char* _str = nullptr;
		size_t _size = 0;
		size_t _capacity = 0;

	public:
		static const int npos;
	};

	const int bit::string::npos = -1;

	void swap(string& x, string& y)
	{
		x.swap(y);
	}

	bool operator==(const string& s1, const string& s2)
	{
		int ret = strcmp(s1.c_str(), s2.c_str());
		return ret == 0;
	}

	bool operator<(const string& s1, const string& s2)
	{
		int ret = strcmp(s1.c_str(), s2.c_str());
		return ret < 0;
	}

	bool operator<=(const string& s1, const string& s2)
	{
		return s1 < s2 || s1 == s2;
	}

	bool operator>(const string& s1, const string& s2)
	{
		return !(s1 <= s2);
	}

	bool operator>=(const string& s1, const string& s2)
	{
		return !(s1 < s2);
	}

	bool operator!=(const string& s1, const string& s2)
	{
		return !(s1 == s2);
	}

	ostream& operator<<(ostream& out, const string& s)
	{
		for (auto ch : s)
		{
			out << ch;
		}

		return out;
	}

	istream& operator>>(istream& in, string& s)
	{
		s.clear();

		char ch;
		//in >> ch;
		ch = in.get();
		char buff[128];
		size_t i = 0;
		while (ch != ' ' && ch != '\n')
		{
			buff[i++] = ch;
			// [0,126]
			if (i == 127)
			{
				buff[127] = '\0';
				s += buff;
				i = 0;
			}

			ch = in.get();
		}

		if (i > 0)
		{
			buff[i] = '\0';
			s += buff;
		}

		return in;
	}

	//istream& operator>>(istream& in, string& s)
	//{
	//	s.clear();
	//	char ch;
	//	//in >> ch;
	//	ch = in.get();
	//	s.reserve(128);
	//	while (ch != '\n' && ch != ' ')
	//	{
	//		s += ch;
	//		ch = in.get();
	//	}

	//	return in;
	//}

	istream& getline(istream& in, string& s)
	{
		s.clear();

		char ch;
		//in >> ch;
		ch = in.get();
		char buff[128];
		size_t i = 0;
		while (ch != '\n')
		{
			buff[i++] = ch;
			// [0,126]
			if (i == 127)
			{
				buff[127] = '\0';
				s += buff;
				i = 0;
			}

			ch = in.get();
		}

		if (i > 0)
		{
			buff[i] = '\0';
			s += buff;
		}

		return in;
	}

	
}

补充:C语言中scanf读取字符串时,' ' 和 '\n' 都是不读取的,读字符时,'\n'不读

           getchar可以读取' '空格字符和'\n'换行字符,gets可读' '空格字符

           C++中cin流' ' 和 '\n' 都是不读取的,要用getline可读' '空格字符,get' ' 和 '\n'都读。

例题

字符串相加

给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和并同样以字符串形式返回。

你不能使用任何內建的用于处理大整数的库(比如 BigInteger), 也不能直接将输入的字符串转换为整数形式。

字符串中第一个唯一字符

 

字符串最后一个单词的长度

#include<iostream>
#include<string>
using namespace std;
int main()
{
 string line;
 // 不要使用cin>>line,因为会它遇到空格就结束了
 // while(cin>>line)

//	char ch;
//	ch = getchar();
//	while (ch != '\n')
//	{
//		line += ch;
//		ch = getchar();
//	}

 while(getline(cin, line))
 {
 size_t pos = line.rfind(' ');
 cout<<line.size()-pos-1<<endl;
 }
 return 0;
}

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你好,赵志伟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值