amar vadalia
amar vadalia

Reputation: 47

iterating string in C, word by word

I just started learning C. What I am trying to right now is that I have two strings in which each word is separated by white spaces and I have to return the number of matching words in both strings. So, is there any function in C where I can take each word and compare it to everyother word in another string, if not any idea on how I can do that.

Upvotes: 2

Views: 1356

Answers (3)

AndersK
AndersK

Reputation: 36082

Break up the first string in words, this you can do in any number of ways everything from looping through the character array inserting \0 at each space to using strtok.

For each word found, go through the other string using strstr which checks if a string is in there. just check return value from strstr, if != NULL it found it.

Upvotes: 1

Will
Will

Reputation: 75625

There are two problems here:

1) splitting each string into words

The strtok() function can split a string into words.

It is a meaningful exercise to imagine how you might write your own equivalent to strtok.

The rosetta project shows both a strtok and a custom method approach to precisely this problem.

I would naturally write my own parser, as its the kind of code that appeals to me. It could be a fun exercise for you.

2) finding those words in one string that are also in another

If you iterate over each word in one string for each word in another, it has O(n*n) complexity.

If you index the words in one string it will take just O(n) which is substantially quicker (if your input is large enough to make this interesting). It is worth imagining how you might build a hashtable of the words in one string so that you can look for the words in the other.

Upvotes: 0

user405725
user405725

Reputation:

I'd not use strtok but stick with pointer arithmetics length comparison and memcmp to compare strings of equal length.

Upvotes: 1

Related Questions