C++ string函数的用法

  • std::string 相当于string
  • string::npos 取值由实现决定,一般是-1

    find_first_of()和 find_last_of()

  • 函数find_first_of()和 find_last_of() 执行简单的模式匹配,
    如在字符串中查找单个字符c。函数find_first_of() 查找在字符串中第1个出现的字符c,
    而函数find_last_of()查找最后一个出现的c。匹配的位置是返回值。如果没有匹配发生,则函数返回-1.

    substr(off,count)

  • 第一个参数off表示下标,count是子串的长度。如果没有越界异常,返回一个[off,off+count)的字符串。  

    erase函数的原型如下:

    1. string& erase ( size_t pos = 0, size_t n = npos );
    2. iterator erase ( iterator position );
    3. iterator erase ( iterator first, iterator last );
      也就是说有三种用法:
    4. erase(pos,n); 删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符
    5. erase(position);删除position处的一个字符(position是个string类型的迭代器)
    6. erase(first,last);删除从first到last之间的字符(first和last都是迭代器)

示例代码:

#include <string>
#include <iostream>
using namespace std;

int main ()
{
string str ("This is an example phrase.");
string::iterator it;
//第(1)种方法
str.erase (10,8);
cout << str << endl; // "This is an phrase."
//第(2)种方法
it=str.begin()+9;
str.erase (it);
cout << str << endl; // "This is a phrase."
//第(3)种方法
str.erase (str.begin()+5, str.end()-7);
cout << str << endl; // "This phrase."
return 0;
}
  • C++编程里面每种容器都定义了一对命名为begin和end的函数,用于返回迭代器,如果容器中有元素的话,由begin返回的迭代器指向第一个元素,由end操作返回的迭代器指向容器的“末端元素的下一个”。

    c_str()

  • c_str()函数返回一个指向正规c字符串的指针,内容和string类的本身对象是一样的,通过string类的c_str()函数能够把string对象转换成c中的字符串的样式

  • 操作c_str()函数的返回值时,只能使用c字符串的操作函数,如:strcpy()等函数.因为,string对象可能在使用后被析构函数释放掉,那么你所指向的内容就具有不确定性.

      
    eg:
    char * name[20];
    string ptr = "tongnono";
    strcpy(name,ptr.c_str());//c_str()返回的是一个临时的指针变量,不能对其操作.

C语言提供了几个标准库函数,可以将任意类型(整型、长整型、浮点型等)的数字转换为字符串。

● itoa():将整型值转换为字符串。
● ltoa():将长整型值转换为字符串。
● ultoa():将无符号长整型值转换为字符串。
● gcvt():将浮点型数转换为字符串,取四舍五入。
● ecvt():将双精度浮点型值转换为字符串,转换结果中不包含十进制小数点。
● fcvt():指定位数为转换精度,其余同ecvt()。
  • 除此外,还可以使用sprintf系列函数把数字转换成字符串,其比itoa()系列函数运行速度慢

C/C++语言提供了几个标准库函数,可以将字符串转换为任意类型(整型、长整型、浮点型等)。

● atof():将字符串转换为双精度浮点型值。
● atoi():将字符串转换为整型值。
● atol():将字符串转换为长整型值。
● strtod():将字符串转换为双精度浮点型值,并报告不能被转换的所有剩余数字。
● strtol():将字符串转换为长整值,并报告不能被转换的所有剩余数字。
● strtoul():将字符串转换为无符号长整型值,并报告不能被转换的所有剩余数字。

find()

  • string类的查找函数:

      
    int find(char c, int pos = 0) const;//从pos开始查找字符c在当前字符串的位置
    int find(const char *s, int pos = 0) const;//从pos开始查找字符串s在当前串中的位置
    int find(const char *s, int pos, int n) const;//从pos开始查找字符串s中前n个字符在当前串中的位置
    int find(const string &s, int pos = 0) const;//从pos开始查找字符串s在当前串中的位置
    //查找成功时返回所在位置,失败返回string::npos的值

往期精彩文章