尊龙游戏旗舰厅官网
收集整理的这篇文章主要介绍了
【c 学习】string类的基本用法
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
概述
string类基本可以看作和char * 类似,只不过前者封装了很多操作,关于char *的不方便性相信用过的人都能深刻感受到,而string类基本解决了这个问题。
基本操作
#include <
string>
// 使用 string 类时须包含这个文件
#include
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类的基本用法的全部内容,希望文章能够帮你解决所遇到的问题。
如果觉得尊龙游戏旗舰厅官网网站内容还不错,欢迎将尊龙游戏旗舰厅官网推荐给好友。