c++怎么提取字符串的一部分

如题所述

C++的string常用截取字符串方法有很多,配合使用以下两种,基本都能满足要求:

find(string strSub, npos);

find_last_of(string strSub, npos);

其中strSub是需要寻找的子字符串,npos为查找起始位置。找到返回子字符串首次出现的位置,否则返回-1;

注:

(1)find_last_of的npos为从末尾开始寻找的位置。

(2)下文中用到的strsub(npos,size)函数,其中npos为开始位置,size为截取大小

例1:直接查找字符串中是否具有某个字符串(返回"2")

std::string strPath = "E:\\数据\\2018\\2000坐标系\\a.shp"

int a = 0;  

if (strPath.find("2018") == std::string::npos)

{

a = 1;

}

else

{

a = 2;

}

return a;

例2:查找某个字符串的字符串(返回“E:”)

std::string strPath = "E:\\数据\\2018\\2000坐标系\\a.shp"

int nPos = strPath.find("\\");

if(nPos != -1)

{

strPath = strPath.substr(0, nPos);

}

return strPath;

扩展资料:

C++中提取字符串的一部分的其他代码:

标准库的string有一个substr函数用来截取子字符串。一般使用时传入两个参数,第一个是开始的坐标(第一个字符是0),第二个是截取的长度。

#include <iostream>

#include <string>

using namespace std;

int main(int argc, char* argv[])

{

string name("rockderia");

string firstname(name.substr(0,4));

cout << firstname << endl;

system("pause");

}

输出结果 rock

温馨提示:答案为网友推荐,仅供参考
相似回答