c++ string 类基本用法样例


[cpp]  view plain copy
  1. #include <string>    //  使用 string 类时须包含这个文件  
  2. #include <iostream>  
  3.   
  4. using namespace std;  
  5.   
  6. int main()  
  7. {  
  8.     string str1;  
  9.      
  10.     //  输入与输出  
  11.     cout << "输入字符串 str1" << endl;  
  12.     cin >> str1; getchar();  
  13.     cout << str1 << endl << endl << endl;  
  14.       
  15.     //  一行行读取   
  16.     cout << "输入字符串 str1" << endl;  
  17.     getline( cin, str1 );  
  18.     cout << str1 << endl;  
  19.   
  20.     //  与 c字符转换  
  21.     string str2("Hello World!"), str3;  
  22.     char   str4[50];  
  23.   
  24.     cout << "输入 C 字符串" << endl;  
  25.     scanf("%s",str4);  
  26.     str3= str4;  
  27.   
  28.     cout << "str2 is " << str2 << endl;  
  29.     cout << "str3 is " << str3 << endl << endl << endl;  
  30.   
  31.     //  求字符串的长度  
  32.     string str5;  
  33.     cout << "输入字符串 str5" << endl;  
  34.     cin >> str5;  
  35.     int   len= str5.size();  
  36.     cout << "字符串 str5的长度为" << len << endl << endl << endl;  
  37.   
  38.     //  遍历字符串例子  
  39.     string str6;  
  40.     cout << "输入字符串 str6" << endl;  
  41.     cin >> str6;  
  42.     int i;  
  43.     for( i= 0; i< str6.size(); ++i )  
  44.     cout << str6[i];  
  45.     cout << endl << endl;  
  46.   
  47.     //  比较两个字符串   比较规则同 c字符串比较规则  
  48.     string str7, str8;  
  49.     cout << "输入字符串 str7, str8 , 中间用空格格开" << endl;  
  50.     cin >> str7 >> str8;  
  51.   
  52.     if( str7< str8 ) cout << str7 << "  小于 " << str8 << endl;  
  53.     else if( str7> str8 ) cout << str7 << "  大于 " << str8 << endl;  
  54.     else cout << str7 << "  等于 " << str8 << endl;  
  55.       
  56.       
  57.     //  字符串与字符相加   
  58.     string str9= "Darren";  
  59.     char ch1= 'a', ch2= 'b';  
  60.     str9= str9+ ch1; cout << str9 << endl << endl;  
  61.     str9= ch2+ str9; cout << str9 << endl << endl << endl;  
  62.       
  63.     //  字符串与字符串相加  
  64.     string str10= "Acm", str11= "ICPC";  
  65.     str10.append( str11 );  
  66.     cout << str10 << endl << endl;  
  67.       
  68.     //  字符串是否包含子串  如果包含 则返回子串在目标串中第一次出现的位置   
  69.     string str12= "I am a student", str13= "student", str14= "aaaaaaa";  
  70.     if( str12.find( str13 )!= -1 )  cout << "Find " << str13 << endl;  
  71.     if( str12.find( str14 )== -1 )  cout << "Not Find  " << str14 << endl;  
  72.       
  73.     //  转换成 c_字符串  
  74.     string str15= "Hello World";  
  75.     printf("%s\n", str15.c_str() );  
  76.        
  77.     system("pause");   
  78.   
  79.     return 0;  
  80. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值