【C++学习】String类的基本用法
概述
string類基本可以看作和char * 類似,只不過前者封裝了很多操作,關于char *的不方便性相信用過的人都能深刻感受到,而string類基本解決了這個問題。
基本操作
#include <string> // 使用 string 類時須包含這個文件 #include <iostream>using namespace std;int main() {string str1;// 輸入與輸出cout << "輸入字符串 str1" << endl;cin >> str1; getchar();cout << str1 << endl << endl << endl;// 一行行讀取 cout << "輸入字符串 str1" << endl;getline( cin, str1 );cout << str1 << endl;// 與 c字符轉換string str2("Hello World!"), str3;char str4[50];cout << "輸入 C 字符串" << endl;scanf("%s",str4);str3= str4;cout << "str2 is " << str2 << endl;cout << "str3 is " << str3 << endl << endl << endl;// 求字符串的長度string str5;cout << "輸入字符串 str5" << endl;cin >> str5;int len= str5.size();cout << "字符串 str5的長度為" << len << endl << endl << endl;// 遍歷字符串例子string str6;cout << "輸入字符串 str6" << endl;cin >> str6;int i;for( i= 0; i< str6.size(); ++i )cout << str6[i];cout << endl << endl;// 比較兩個字符串 比較規則同 c字符串比較規則string str7, str8;cout << "輸入字符串 str7, str8 , 中間用空格格開" << endl;cin >> str7 >> str8;if( str7< str8 ) cout << str7 << " 小于 " << str8 << endl;else if( str7> str8 ) cout << str7 << " 大于 " << str8 << endl;else cout << str7 << " 等于 " << str8 << endl;// 字符串與字符相加 string str9= "Darren";char ch1= 'a', ch2= 'b';str9= str9+ ch1; cout << str9 << endl << endl;str9= ch2+ str9; cout << str9 << endl << endl << endl;// 字符串與字符串相加string str10= "Acm", str11= "ICPC";str10.append( str11 );cout << str10 << endl << endl;// 字符串是否包含子串 如果包含 則返回子串在目標串中第一次出現的位置 string str12= "I am a student", str13= "student", str14= "aaaaaaa";if( str12.find( str13 )!= -1 ) cout << "Find " << str13 << endl;if( str12.find( str14 )== -1 ) cout << "Not Find " << str14 << endl;// 轉換成 c_字符串string str15= "Hello World";printf("%s\n", str15.c_str() );system("pause"); return 0; }字符串分割
字符串分割主要利用find函數和substr函數
1、find函數
原型:size_t find ( const string& str, size_t pos = 0 ) const;
功能:查找子字符串第一次出現的位置。
參數說明:str為子字符串,pos為初始查找位置。
返回值:找到的話返回第一次出現的位置,否則返回string::npos
2、substr函數
原型:string substr ( size_t pos = 0, size_t n = npos ) const;
功能:獲得子字符串。
參數說明:pos為起始位置(默認為0),n為結束位置(默認為npos)
返回值:子字符串
另外關于查找子串還有更多的方法:find, find_last_of, find_last_not_of, rfind。參看鏈接.
轉換(int,string,char*,CString)
這篇寫得比較全:http://blog.csdn.net/sha_jinhao/article/details/8463103
參考資料
1. c++ string 類基本用法樣例:http://www.cppblog.com/Darren/archive/2009/03/13/76474.html
2. char*,string和CString之間的轉換:http://blog.csdn.net/sha_jinhao/article/details/8463103
3. 字符串分割(C++):http://www.cnblogs.com/MikeZhang/archive/2012/03/24/MySplitFunCPP.html
本文用菊子曰發布轉載于:https://www.cnblogs.com/xweiwei/archive/2013/05/01/3053725.html
總結
以上是生活随笔為你收集整理的【C++学习】String类的基本用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Sicily 1694. Spiral
- 下一篇: 11.2.0.2 HAIP