c++ string 操作汇总

2018-03-15  本文已影响0人  江南竹影

欢迎访问我的个人博客:zengzeyu.com

前言


作为传递信息的载体string数据类型广泛应用于各种编程语言中,尤其在轻量化语言 Python 中发挥的淋漓尽致,通过string传递信息 Python 使各个模块组装在一起完成指定的工作任务,这也是 Python 被称为“胶水语言”的原因。
本文着眼于 c++string的应用。首先建议先浏览string在线文档,这其中包含了大多数日常所需函数。

正文


1. string 内查找字符串str

std::string::find(str)函数:http://www.cplusplus.com/reference/string/string/find/
Example

// string::find
#include <iostream>       // std::cout
#include <string>         // std::string

int main ()
{
  std::string str ("There are two needles in this haystack with needles.");
  std::string str2 ("needle");

  // different member versions of find in the same order as above:
  std::size_t found = str.find(str2);
  if (found!=std::string::npos)
    std::cout << "first 'needle' found at: " << found << '\n';

  found=str.find("needles are small",found+1,6);
  if (found!=std::string::npos)
    std::cout << "second 'needle' found at: " << found << '\n';

  found=str.find("haystack");
  if (found!=std::string::npos)
    std::cout << "'haystack' also found at: " << found << '\n';

  found=str.find('.');
  if (found!=std::string::npos)
    std::cout << "Period found at: " << found << '\n';

  // let's replace the first needle:
  str.replace(str.find(str2),str2.length(),"preposition");
  std::cout << str << '\n';

  return 0;
}

其中 npos 值为 -1,用于判断。
其他查找功能类函数:

2. string内删除目标str

substr: 本质还是查找目标str
Example

// string::substr
#include <iostream>
#include <string>

int main ()
{
  std::string str="We think in generalities, but we live in details.";
                                           // (quoting Alfred N. Whitehead)

  std::string str2 = str.substr (3,5);     // "think"

  std::size_t pos = str.find("live");      // position of "live" in str

  std::string str3 = str.substr (pos);     // get from "live" to the end

  std::cout << str2 << ' ' << str3 << '\n';

  return 0;
}

3. 字符串分割

字符串分割推荐使用 std::stringstream 作为中间载体和 getline() 函数组合来完成。
以分割字符 “ ; ”为例:

void splitPathStr(std::string& path_str)
{
    std::vector<std::string> filelists;
    std::stringstream sstr( path_str );
    std::string token;
    while(getline(sstr, token, ';'))
    {
        filelists.push_back(token);
    }
}

4. int型与string型互相转换

int型转string

void int2str(const int &int_temp,string &string_temp)  
{  
        stringstream stream;  
        stream<<int_temp;  
        string_temp=stream.str();   //此处也可以用 stream>>string_temp  
}  

string型转int

void str2int(int &int_temp,const string &string_temp)  
{  
    stringstream stream(string_temp);  
    stream>>int_temp;  
} 

未完待续...

以上。


参考文献:

  1. c++ reference
  2. C++中int、string等常见类型转换
上一篇下一篇

猜你喜欢

热点阅读