Home > Blockchain >  Is there a function that gives you index of last char substring in string?
Is there a function that gives you index of last char substring in string?

Time:10-28

The find() function gives you index of first char of substring in string, I need last char.

I tried to get length of substring and sum it to first index but it is going out of bound.

if( str2.substr(last char index, 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));

CodePudding user response:

You can try to do something like the below helper function I made. It returns the index of the last character of the substring.

Stepwise details:

  1. Find the substring: this gives the index of the first char of the substring.
  2. If the index is out of bound, return -1 to denote that the substring cannot be found.
  3. Else if the index is valid, add it to the length of the substring - 1. This is done to get the index of the actual character.
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;
}

CodePudding user response:

You can do something like:

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`
}
  • Related