#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;
}
c++ string 类基本用法样例
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章
2020 重学C++ 重构你的C++知识体系
wy53780
2020-04-23 14:13:15
现代C++实战30讲
wy53780
2020-04-23 13:58:44
node遇上c++ --- 爱情来的太快(一) (没有文章)
sewerganger
2019-02-24 22:55:07
近期前端发展计划
Ashleysweetie
2019-02-24 22:32:41
Xcode与C++之游戏开发:Pong游戏
優惠碼優惠
2019-02-24 19:41:23
C++回声服务器_2-修复客户端问题
chenBright
2019-02-24 12:55:03
C++面试基础之static关键字详解
riccoqu
2019-02-24 12:42:54
[C++回声服务器_1]简单版本
chenBright
2019-02-23 15:42:37
双向链表(不带头结点)
toigel
2019-02-23 13:43:42
Windows server 2003 *** 配置实例
czq2008sky
2019-02-23 13:38:34
Windows server 2003 *** 配置实例(Site to Site)
czq2008sky
2019-02-23 13:38:34
Android平台调用WebService详解
推薦碼發放
2019-02-24 19:41:33
Spring Cloud Alibaba基础教程:支持的几种服务消费方式(RestTemplate、WebClient、Feign)
程序猿dd
2019-02-24 10:41:27
【Go】string 也是引用类型
thinkeridea
2019-02-24 08:04:44