find() 函式為您提供字串中子字串的第一個字符的索引,我需要最后一個字符。
我試圖獲取子字串的長度并將其與第一個索引相加,但它超出了界限。
if(str2.substr(最后一個字符索引,str2.find(part3)))
int sizeOfPart2 = part2.length();
int sizeOfPart3 = part3.length();
if(sizeOfPart2 == 1){
sizeOfPart2 = 0;
}
else if(sizeOfPart3 == 1){
sizeOfPart3 = 0;
}
cout<<str2.substr(str2[str2.find(part2) sizeOfPart2],
str2.find(part3));
uj5u.com熱心網友回復:
您可以嘗試執行以下我制作的輔助函式。它回傳子字串最后一個字符的索引。
分步細節:
- 查找子字串:這給出了子字串的第一個字符的索引。
- 如果索引超出范圍,則回傳 -1 表示找不到子字串。
- 否則,如果索引有效,則將其添加到子字串的長度 - 1。這樣做是為了獲取實際字符的索引。
int findLastCharSubstring(std::string text, std::string substring){
int index = text.find(substring);
if(index != std::string::npos) // If in bound, return correct index
return index substring.length() - 1;
else // If out of bound return -1, i.e. not found
return -1;
}
uj5u.com熱心網友回復:
您可以執行以下操作:
const std::string path = "repeatedstrieang";
std::string mysubstr = "ea";
auto firstCharPos = path.find("ea");
if(firstCharPos!=std::string::npos)
{
std::cout << firstCharPos mysubstr.size() -1; //-1 because indexing starts from `0`
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/522349.html
標籤:C 细绳功能
