Sub Strings

Hi
Problem: I have a large text string and within that large text string I need to look for 30 different words to see if they are part of that text string. And of the 30 target words that are in the text string I need to order them as to which came first, second, third,..., last etc...

Ideally there would be a substring library that returned an integer value to where in the large text string the target string(s) was found and I could do a sort based on the return value(s). But it looks like the only substring library in C returns a pointer to where the substring was found.

Example:
"I have three pets, a dog a cat and a pig"

Target #1: cat
Target #2: pig
Target #3: dog
Target #4: cow

Somehow, I need to know that the order the target strings appeared in were dog, cat and then pig.

Any thoughts on how I could easily do this?

LASims
Last edited on
Do you use C-strings or C++ std::string?
If the former, strstr is for you.
http://en.cppreference.com/w/cpp/string/byte/strstr

In latter case you have wide array of choices from std::sring's find member (which returns array subscript) to std::search algorithm which operaes on and returns iterators.

I need to order them as to which came first, second, third,..., last etc...
...
it looks like the only substring library in C returns a pointer to where the substring was found.
Why not sort pointers themselves? They have a total ordering if they belong to same array.
Last edited on
C Strings, like strstr()

strstr() returns pointer. How to compare which comes first with that?
How to compare which comes first with that?
Exactly same way as you would compare two integers


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <cstring>

int main()
{
    const char* string = "A dog is chasing cat";
    const char* cat = strstr(string, "cat");
    const char* dog = strstr(string, "dog");
    if(!(cat && dog)) {
        std::cerr << "One of the words was not found\n";
        return 1;
    }
    if(cat < dog)
        std::cout << "dog comes after cat\n";
    else
        std::cout << "dog comes before cat\n";
}

deleted
Last edited on
use a std::map , it is like a dictionary . Combine it with std::algorithm and it should work fine . I am assuming that you have a text and that you want to find indexation of words .
Solved now. The MiiNiPaa solution worked good. I just made an array of character pointers and can sort by it.

 
const char* teamPos[MAX_TEAMS];
Topic archived. No new replies allowed.