+ 2

How to compare a single word of multi word string to another multi word string?

For e.g I want to compare these two Str1- Mary has lamb Str2- I have lamb and sheep So here in both lamb is common. Then how am I supposed to write this in code where two strings are entered by user and in output common word is printed.

12th Sep 2020, 4:04 PM
Sneha Bisht
Sneha Bisht - avatar
4 Antworten
+ 4
You can use sscanf() to read one word at a time from Str1. Then maybe use strstr() to find whether each word is in Str2. Now there is another problem to tackle. Example: Str1 "find a word", Str2 "a boat floats". strstr() will find "a" in all three words of Str2. Only one of them is a whole word. I have solved this by adding space delimiters. Instead of searching for "a", surround it with space delimiters, like " a ". Also surround Str2 with space delimiters like " a boat floats ". Now strstr() will find only whole word matches.
12th Sep 2020, 5:08 PM
Brian
Brian - avatar
+ 2
Although you can use loops to perform character by character comparison but in C there is a built-in library function(in <string.h> header) strcmp() which can be used for that purpose. Learn more about it here👇 https://www.geeksforgeeks.org/strcmp-in-c-cpp/
12th Sep 2020, 4:23 PM
Arsenic
Arsenic - avatar
+ 2
Arsenic strcmp() would compare whole string or can we use it compare a part of string line as in case I've asked above.
12th Sep 2020, 4:26 PM
Sneha Bisht
Sneha Bisht - avatar
+ 2
Sneha Bisht strcmp() compares whole string.
13th Sep 2020, 1:18 AM
Arsenic
Arsenic - avatar