C/C++字符串string操作的全面总结(二)

3、适合string类型操作的函数

substr()主要功能是复制子字符串,要求从指定位置开始,并具有指定的长度。

append() 方法在被选元素的结尾(仍然在内部)插入指定内容。提示:如需在被选元素的开头插入内容,请使用prepend()方法。

replace() 该函数返回一个字符串,其中指定的字符串已经被替换为另一字符串,并且替换的次数也可以指定。


下面是代码实例:

#include <iostream>
#include <string>

using namespace std;
//公众号:C语言与CPP编程

int main()
{
  string s("Hello world");
  string s2 = s.substr(6,5);  //从第6个开始取5个
  cout << s2 << endl ;        //s2为world

  s2 = s.substr(6);  //从第6个开始取拷贝所有的
  cout << s2 << endl ;        //s2为world

  s2 = s.substr(6);    //s2拷贝s的全部,相当于s2=s
  cout << s2 << endl ;  //s2为Hello world

  s = "C++ Primer";
  s.append(" 3rd Ed");   //再s最后添加3rd Ed
  cout << s<< endl ;  //s为C++ Primer 3rd Ed

  s = "C++ Primer";
  s.insert(s.size()," 3rd Ed"); //最后插入
  cout << s<< endl ;  //s为C++ Primer 3rd Ed

  s.replace(11,3,"4th");       //下标11开始3个替换4th
    cout << s<< endl ;  //s为C++ Primer 4th Ed

  s.replace(11,3,"Fourth");       //下标11开始3个替换Fourth
    cout << s<< endl ;  //s为C++ Primer Fourth Ed

  s = "C++ Primer 3rd Ed";    //replace相当于先删除后插入
  s.erase (11,3);            //删除3rd
  s.insert(11,"Fourth");      //插入Fourth
  cout << s<< endl ;  //s为C++ Primer Fourth Ed

  return 0;
}

4、string类型的查找

s.find( args); //在 s 中查找 args 的第一次出现

s.rfind( args) // 在 s 中查找 args 的最后一次出现

s.find_first_of( args) //在 s 中查找 args 的任意字符的第一次出现

s.find_last_of( args) //在 s 中查找 args 的任意字符的最后一次出现

s.find_first_not_of( args) //在 s 中查找第一个不属于 args 的字符

s.find_last_not_of( args) //在 s 中查找最后一个不属于 args 的字符

#include <iostream>
#include <string>

using namespace std;
// 公众号:C语言与CPP编程

int main()
{
  string name("AnnaBelle");
  string::size_type pos1 = name.find("Bell");  
  cout << pos1 << endl;     //返回下标4,如果没找到返回npos

  if(pos1 == string::npos)
     cout << "没找到!" << endl; 
  else
     cout << "找到了!下标:" << pos1 <<endl; 

  name = "2sn3";
  string numerics("0123456789");
  string::size_type pos = name.find_first_of(numerics);  //在2sn3中查找0123456789中任意一个第一次出现
  if(pos == string::npos)
     cout << "没找到!" << endl; 
  else
     cout << "找到了!下标:" << pos <<endl;       //找到了!下标:1

  //其他类型的查找这里就不举例子了

  return 0;
}
5、string对象的比较
#include <iostream>
#include <string>
#include <cctype>
using std::cout;
using std::endl;
using std::cin;
using std::string;
int main(void){
  string str1="hi,test,hello";
  string str2="hi,test";
  //字符串比较
  if(str1.compare(str2)>0)
    printf("str1>str2\n");
  else if(str1.compare(str2)<0)
    printf("str1<str2\n");
  else
    printf("str1==str2\n");

  //str1的子串(从索引3开始,包含4个字符)与str2进行比较
  if(str1.compare(3,4,str2)==0)
    printf("str1的指定子串等于str2\n");
  else
    printf("str1的指定子串不等于str2\n");

  //str1指定子串与str2的指定子串进行比较
  if(str1.compare(3,4,str2,3,4)==0)
    printf("str1的指定子串等于str2的指定子串\n");
  else
    printf("str1的指定子串不等于str2的指定子串\n");

  //str1指定子串与字符串的前n个字符进行比较
  if(str1.compare(0,2,"hi,hello",2)==0)
    printf("str1的指定子串等于指定字符串的前2个字符组成的子串\n");
  else
    printf("str1的指定子串不等于指定字符串的前2个字符组成的子串\n");
  return 0;

}

上一篇:nuget管理插件


下一篇:VS2015 NuGet错误:远程证书无效