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

比如有一串string s="ABAB"中,我想提取前面一半,也就是s="AB",(注意s不变)怎么做到,求助
s不变的意思是变量名还是s

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

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-24

C++的string类提供了大量的字符串操作函数,提取字符串的一部分,可采用substr函数实现:

    头文件:

    #include <string> //注意没有.h  string.h是C的标准字符串函数数,c++中一般起名为ctring.  而string头文件是C++的字符串头文件。

    函数原型:

    string substr(int pos = 0,int n ) const;

    函数说明:

    参数1pos是可缺省参数,默认为0,即:从字符串头开始读取。

    参数2n表示取多少个字符

    该函数功能为:返回从pos开始的n个字符组成的字符串,原字符串不被改变

参考代码:

#include <iostream>
#include <string>
using namespace std ;
void main()
{
    string s="ABAB";
    cout << s.substr(2) <<endl ; //输出AB
    cout << s.substr(0,2) <<endl ; //同上
    cout << s.substr(1,2) <<endl ; //输出BA
}

第2个回答  2015-09-23

可以利用C++的string类的成员函数substr提取字符串的一部分。举例代码台下:

//#include "stdafx.h"//If the vc++6.0, with this line.
#include <string>
#include <iostream>
using namespace std;
int main(void){
    string s="ABAB";
    cout << s.substr(0,2) << endl;//0表示从0下标开始,2表示截取2位
    return 0;
}

第3个回答  2013-12-13
string str1 = "ABAB";
string str2 = str1.Substring(0, 2);

// str1.Substring(0, 2); 其中0表示要取得字符串的起始位置,2就是要取得字符串的长度 结果是"AB";追问

Substring没有定义,要引入库吗,反正不行。。。

追答

#include
using namespac std;

本回答被网友采纳
第4个回答  推荐于2017-09-03
#include <string>
#include <iostream>

using namespace std;

int main()
{
string s="ABAB";
char a[100];
strncpy(a,s.c_str(),s.length()/2);
cout<<a<<endl;
}

本回答被提问者采纳
相似回答