C++问题string的一些用法示例

来源:互联网 发布:银河证券海王星软件 编辑:程序博客网 时间:2024/06/07 20:54
From:http://hi.baidu.com/necrohan/blog/item/50c84a13eff7af25dc540140.html

//sstrchng.cpp
//changing parts of string objects
#include <iostream>
#include <string>
using namespace std;

int main()
   {
   string s1("Quick! Send for Count Graystone.");
   string s2("Lord");
   string s3("Don't ");

   s1.erase(0, 7);               //remove "Quick! "
   s1.replace(9, 5, s2);         //replace "Count" with "Lord"
   s1.replace(0, 1, "s");        //replace 'S' with 's'
   s1.insert(0, s3);             //insert "Don't " at beginning
   s1.erase(s1.size()-1, 1);     //remove '.'
   s1.append(3, '!');            //append "!!!"

   int x = s1.find(' ');         //find a space
   while( x < s1.size() )        //loop while spaces remain 如果找不到返回-1为何还会退出?是怎么跳出来的?
      {
      s1.replace(x, 1, "/");     //replace with slash
      x = s1.find(' ');          //find next space
      cout<<x<<" - "<<s1.size()<<" - "<<(x-s1.size())<<endl;
      }
//    cout << "s1: " << s1 << endl;
   cout<<"string::npos: "<<string::npos<<endl;
   cout<<static_cast<unsigned int>(10-32)<<endl;//测试无符号整数计算结果
   return 0;
   }



// 输出:
// 10 - 32 - 4294967274
// 14 - 32 - 4294967278
// 19 - 32 - 4294967283
// -1 - 32 - 4294967263
// string::npos: 4294967295
// 4294967274
// Press any key to continue

// find函数找不到的时候返回的是string::npos,找到返回index
// 因此,s1.size()结果是无符号整数,在计算(x-s1.size())时把int类型的x转换为无符号整数
// int 最大表示2147483647 *2=4294967294,-1即4294967295,
// 因此x=-1时,x < s1.size()被转为无符号整数判断,大于字符串长度32
// 可能string函数返回的都是无符号整数
原创粉丝点击