C++字符串的截取問題
C++字符串截取
按照字符串截取
/**
?* @brief ? 按照指定的字符串截取字符串
?* @param str ?需要截取的字符串
?* @param ?pattern ?按照該字符串截取
?* @return 截取好的字符串vector
?*/
std::vector<std::string> splitStr(std::string str, std::string pattern)
{
? ? std::string::size_type pos;
? ? std::vector<std::string> result;
? ? //擴(kuò)展字符串以方便操作
? ? str += pattern;
? ? int size = str.size();
? ? for (int i = 0; i < size; i++)
? ? {
? ? ? ? pos = str.find(pattern, i);
? ? ? ? if (pos < size)
? ? ? ? {
? ? ? ? ? ? std::string s = str.substr(i, pos - i);
? ? ? ? ? ? result.push_back(s);
? ? ? ? ? ? i = pos + pattern.size() - 1;
? ? ? ? }
? ? }
? ? return result;
}按照字符截取
/**
?* @brief ? 按照指定的字符截取字符串
?* @param str ?需要截取的字符串
?* @param ?pattern ?按照該字符截取
?* @return 截取好的字符串vector
?*/
std::vector<std::string> splitStr(std::string str, char pattern)
{
? ? // 擴(kuò)展字符串,方便后面進(jìn)行操作
? ? str.push_back(pattern);
? ? std::vector<std::string> result;
? ? auto iter = str.cbegin();
? ? auto iter2 = iter;
? ? for (iter; iter != str.cend(); ++iter)
? ? {
? ? ? ? if (*iter == pattern)
? ? ? ? {
? ? ? ? ? ? result.push_back(string(iter2, iter));
? ? ? ? ? ? iter2 = iter + 1;
? ? ? ? }
? ? }
? ? return result;
}C++截取部分字符串(類似python的切片)
1.首先在python中取一個(gè)字符串的多少位,使用s[begin:end]。
2.c++中使用一個(gè)函數(shù)來截取字符串位
頭文件:
#include <string> //注意沒有.h string.h是C的標(biāo)準(zhǔn)字符串函數(shù)數(shù),c++中一般起名為ctring. 而string頭文件是C++的字符串頭文件。
函數(shù)原型:
string substr(int pos = 0,int n ) const;
參數(shù)說明:
- 參數(shù)1:pos是必填參數(shù)
- 參數(shù)2:n是可參數(shù),表示取多少個(gè)字符,不填表示截取到末尾
該函數(shù)功能為:返回從pos開始的n個(gè)字符組成的字符串,原字符串不被改變
# include <iostream>
# include <string>
using namespace std;
int main()
{
? ? const string image_name = "0170.bmp";
? ? print(image_name.substr(0, 4));
? ? return 0;
}總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
C語言用封裝方法實(shí)現(xiàn)飛機(jī)大戰(zhàn)游戲
這篇文章主要為大家詳細(xì)介紹了C語言用封裝方法實(shí)現(xiàn)飛機(jī)大戰(zhàn)游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05
C語言數(shù)據(jù)結(jié)構(gòu) 雙向鏈表的建立與基本操作
這篇文章主要介紹了C語言數(shù)據(jù)結(jié)構(gòu) 雙向鏈表的建立與基本操作的相關(guān)資料,需要的朋友可以參考下2017-03-03
OpenCV邊緣提取算法流程的實(shí)現(xiàn)(附DEMO)
本文主要介紹了OpenCV邊緣提取算法流程的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08
C語言數(shù)據(jù)結(jié)構(gòu)與算法之隊(duì)列的實(shí)現(xiàn)詳解
隊(duì)列只允許在一端進(jìn)行插入數(shù)據(jù)操作,在另一端進(jìn)行刪除數(shù)據(jù)操作的特殊線性表,隊(duì)列具有先進(jìn)先出FIFO(First In First Out)的原則。本文將通過實(shí)例詳細(xì)說說隊(duì)列的實(shí)現(xiàn),需要的可以學(xué)習(xí)一下2022-10-10

