-1

Hello I been trying to find a way of finding a string of characters within two characters. How should I go about doing this in c++?

sdfgkjr$joeisawesome$sdfeids -> joeisawesome

EDIT: The other answer is looking for if a string exist within a string. I'm looking for a string within two characters and outputting the sting within the two chars. Thank you for looking PoX.

TheDT
  • 3
  • 3
  • 1
    Maybe using [`find`](http://en.cppreference.com/w/cpp/string/basic_string/find)? – Kerrek SB Jan 16 '16 at 02:10
  • Possible duplicate of [How to find substring from string?](http://stackoverflow.com/questions/13195353/how-to-find-substring-from-string) – PoX Jan 16 '16 at 02:13
  • Do you want the solution for its own sake, or are you trying to improve your skills? Would you rather use `find` and get the answer, or write your own function as an exercise? – Beta Jan 16 '16 at 03:02
  • I would like any help you're willing to offer. A solution would be awesome; however, if you could just give me an idea of what I would need to do that would be awesome too. Thanks in advance. – TheDT Jan 16 '16 at 04:00

1 Answers1

1

Okay, so when you say two characters, I'm assuming that you are referring to delimiters. In this case you would have to use String.find() to find the position of the delimiters. After finding the positions of the delimiters, you can can use String.substr(index1,index2-index1) to return the substring.

Example:

#include <iostream>
#include <string>

int main()
{
    std::size_t index1,index2;
    std::string myString = "sdfgkjr$joeisawesome$sdfeids";
    std::string sub= "";
    index1 = myString.find('$');

    //string::npos is -1 if you are unaware

    if(index1!=std::string::npos&& index1<myString.length()-1)
        index2=myString.find('$',index1+1);
    if(index2!=std::string::npos)
    {
        sub = myString.substr(index1+1,index2-index1);
    }   
    std::cout<<sub; //outputs joeisawesome
}
Alan S.
  • 156
  • 1
  • 1
  • 4
  • Please let me know if I am misunderstanding your question and this is not what you are looking for. – Alan S. Jan 16 '16 at 04:13
  • Thank you so much! This is exactly what I was trying to do. For some reason it has a $ at the beginning but no biggy. – TheDT Jan 16 '16 at 05:06
  • No problem -- I'm happy to help. I fixed the code. The final function call should be myString.substr(index+1, index2-index1). Now it will output the correct value. – Alan S. Jan 16 '16 at 05:38
  • Oh thank you Alan! I did edit that line however when adding the +1 to the index1 value it pushes the other delimiter into the output so I put a -1 after index2 like so `sub = myString.substr(index1+1, index2-1 - index1);` – TheDT Jan 17 '16 at 04:43