-
Strings
Hey all,
I can't figure out how to do this at all.... hopeing someone could help.
I have a string containing groups of two charactors. For the sake of this article they can be random:
"bh oj wh qx"
The string varies in length, ie in number of groups, but always has at least 2 and no more than 6 groups.
I need to search this string to see if ANY group of charactors occues twice. For instance:
"aj df qw xa df"
So in pseudocode, I figure I can do something like this:
Code:
For each group in string
check with all other groups in that string to see if its equal
I've been unable to find any functions on google that tell me if a string contains a groups of chars like this.
An help woud be highly apreiciated.
-
-
From http://www.phim.unibe.ch/comp_doc/c_...PLES/strstr.c:
Code:
char string[]="string to search";
char test[]="sear";
/* strstr returns a pointer into 'string'
* if 'test' is found' if not found, NULL
* is returned. */
if (strstr(string, test)) puts("String found");
So... that leaves the question, how can I do a for loop for each of the groups, rather than a single char? I'm sorry... strings and poitners are absolutly my weak point.
Thanks
-
You can loop it, and when it find the occurance of the substring it will return a pointer to it and then you can use that as the source string for another round of strstr()'s.
-
OK, but I'm not searching for a particular starting string, I'm searching for only second occurences of groups already present. Running through every 2-char combo would be a little inefficient...
Thanks
-
Something along this line?
Code:
#include <stdio.h>
#include <string.h>
int main()
{
const char example[] = "aj df qww xa df ao aj df qww";
const char first[7], *start = example, *match, *ptr;
while ( sscanf(start, "%6s", first) == 1 )
{
size_t len = strlen(first);
printf("first = \"%s\"\n", first);
if ( !start[len] )
{
break;
}
start += len + 1;
ptr = start;
while ( match = strstr(ptr, first) )
{
printf(" match = \"%s\"\n", match);
ptr = match + 3;
}
}
return 0;
}
/* my output
first = "aj"
match = "aj df qww"
first = "df"
match = "df ao aj df qww"
match = "df qww"
first = "qww"
match = "qww"
first = "xa"
first = "df"
match = "df qww"
first = "ao"
first = "aj"
first = "df"
first = "qww"
*/
-
Yeah, the algorithm may be as this:
1. extract substring.
2. traverse the storage, looking for duplicate (storage explained below)
2. 'remember' substring in some storage (put it in the array, linked list, hash etc)
3. loop to step 1