Skip to main content

Find common words in two strings

Here given code implementation process.

import java.util.HashMap;
/*
    Java program for
    Find common words in two strings
*/
public class Similarity
{
	public void commonWords(String str1, String str2)
	{
		HashMap < String, Boolean > record = new HashMap < String, Boolean > ();
		// Assume that  string contains valid words
		String[] str1Words = str1.split(" ");
		String[] str2Words = str2.split(" ");
		if (str1Words.length == 0 || str2Words.length == 0)
		{
			// One string is empty
			return;
		}
		for (int i = 0; i < str1Words.length; ++i)
		{
			if (!record.containsKey(str1Words[i]))
			{
				// Here false are indicates this word exist in first string
				record.put(str1Words[i], false);
			}
		}
		for (int i = 0; i < str2Words.length; ++i)
		{
			if (record.containsKey(str2Words[i]))
			{
				// Here true are indicates this word exist in both string
				record.put(str2Words[i], true);
			}
		}
		for (String info: record.keySet())
		{
			if (record.get(info))
			{
				System.out.println(info);
			}
		}
	}
	public static void main(String[] args)
	{
		Similarity task = new Similarity();
		// Input strings
		String str1 = "Test Mango orange pineapple and lemons";
		String str2 = "Mango is sweet but lemons are sour Test";
		task.commonWords(str1, str2);
	}
}

Output

Test
Mango
lemons
// Include header file
#include <iostream>
#include <string.h>
#include <unordered_map>

using namespace std;
/*
    C++ program for
    Find common words in two strings
*/
class Similarity
{
    public: void commonWords(char str1[], char str2[])
    {
        unordered_map < string, bool > record;
        // Assume that  string contains valid words
        char *str1Words = strtok(str1, " ");


        bool status = false;
    

       
        while (str1Words != NULL)
        {
            if (record.find(str1Words) == record.end())
            {
                // Here false are indicates this word exist in first string
                record[str1Words] = false;
            }
            str1Words = strtok(NULL, " ");
        }

        char *str2Words = strtok(str2, " ");
        while (str2Words!=NULL)
        {
          
            if (record.find(str2Words) != record.end())
            {
                // Here true are indicates this word exist in both string
                record[str2Words] = true;
            }

            str2Words = strtok(NULL, " ");
        }

        for (auto &info: record)
        {
            if (info.second)
            {
               cout << info.first << endl;
            }
        }
    }
};
int main()
{
    Similarity *task = new Similarity();
    // Input strings
    char str1[] = "Test Mango orange pineapple and lemons";
    char str2[] = "Mango is sweet but lemons are sour Test";
    task->commonWords(str1, str2);
    return 0;
}

Output

Mango
Test
lemons
// Include namespace system
using System;
using System.Collections.Generic;
/*
    Csharp program for
    Find common words in two strings
*/
public class Similarity
{
	public void commonWords(String str1, String str2)
	{
		Dictionary < string, bool > record = 
          new Dictionary < string, bool > ();
		// Assume that  string contains valid words
		String[] str1Words = str1.Split(" ");
		String[] str2Words = str2.Split(" ");
		if (str1Words.Length == 0 || str2Words.Length == 0)
		{
			// One string is empty
			return;
		}
		for (int i = 0; i < str1Words.Length; ++i)
		{
			if (!record.ContainsKey(str1Words[i]))
			{
				// Here false are indicates this word exist in first string
				record.Add(str1Words[i], false);
			}
		}
		for (int i = 0; i < str2Words.Length; ++i)
		{
			if (record.ContainsKey(str2Words[i]))
			{
				// Here true are indicates this word exist in both string
				record[str2Words[i]] = true;
			}
		}
		foreach(KeyValuePair < String, bool > info in record)
		{
			if (info.Value)
			{
				Console.WriteLine(info.Key);
			}
		}
	}
	public static void Main(String[] args)
	{
		Similarity task = new Similarity();
		// Input strings
		String str1 = "Test Mango orange pineapple and lemons";
		String str2 = "Mango is sweet but lemons are sour Test";
		task.commonWords(str1, str2);
	}
}

Output

Test
Mango
lemons
package main
import "strings"
import "fmt"
/*
    Go program for
    Find common words in two strings
*/
func commonWords(str1, str2 string) {
	var record = make(map[string] bool)
	// Assume that  string contains valid words
	var str1Words = strings.Split(str1, " ")
	var str2Words = strings.Split(str2, " ")
	if len(str1Words) == 0 || len(str2Words) == 0 {
		// One string is empty
		return
	}
	for i := 0 ; i < len(str1Words) ; i++ {
		if _, found := record[str1Words[i]] ; !found {
			// Here false are indicates this word exist in first string
			record[str1Words[i]] = false
		}
	}
	for i := 0 ; i < len(str2Words) ; i++ {
		if _, found := record[str2Words[i]] ; found {
			// Here true are indicates this word exist in both string
			record[str2Words[i]] = true
		}
	}
	for k, v := range record {
		if v {
			fmt.Println(k)
		}
	}
}
func main() {
	
	// Input strings
	var str1 string = "Test Mango orange pineapple and lemons"
	var str2 string = "Mango is sweet but lemons are sour Test"
	commonWords(str1, str2)
}

Output

Test
Mango
lemons
<?php
/*
    Php program for
    Find common words in two strings
*/
class Similarity
{
	public	function commonWords($str1, $str2)
	{
		$record = array();
		// Assume that  string contains valid words
		$str1Words = explode(" ", $str1);
		$str2Words = explode(" ", $str2);
		if (count($str1Words) == 0 || count($str2Words) == 0)
		{
			// One string is empty
			return;
		}
		for ($i = 0; $i < count($str1Words); ++$i)
		{
			if (!array_key_exists($str1Words[$i], $record))
			{
				// Here false are indicates this word exist in first string
				$record[$str1Words[$i]] = false;
			}
		}
		for ($i = 0; $i < count($str2Words); ++$i)
		{
			if (array_key_exists($str2Words[$i], $record))
			{
				// Here true are indicates this word exist in both string
				$record[$str2Words[$i]] = true;
			}
		}
		foreach($record as $key => $value)
		{
			if ($value)
			{
				echo($key."\n");
			}
		}
	}
}

function main()
{
	$task = new Similarity();
	// Input strings
	$str1 = "Test Mango orange pineapple and lemons";
	$str2 = "Mango is sweet but lemons are sour Test";
	$task->commonWords($str1, $str2);
}
main();

Output

Test
Mango
lemons
/*
    Node JS program for
    Find common words in two strings
*/
class Similarity
{
	commonWords(str1, str2)
	{
		var record = new Map();
		// Assume that  string contains valid words
		var str1Words = str1.split(" ");
		var str2Words = str2.split(" ");
		if (str1Words.length == 0 || str2Words.length == 0)
		{
			// One string is empty
			return;
		}
		for (var i = 0; i < str1Words.length; ++i)
		{
			if (!record.has(str1Words[i]))
			{
				// Here false are indicates this word exist in first string
				record.set(str1Words[i], false);
			}
		}
		for (var i = 0; i < str2Words.length; ++i)
		{
			if (record.has(str2Words[i]))
			{
				// Here true are indicates this word exist in both string
				record.set(str2Words[i], true);
			}
		}
		for (let [key, value] of record)
		{
			if (value)
			{
				console.log(key);
			}
		}
	}
}

function main()
{
	var task = new Similarity();
	// Input strings
	var str1 = "Test Mango orange pineapple and lemons";
	var str2 = "Mango is sweet but lemons are sour Test";
	task.commonWords(str1, str2);
}
main();

Output

Test
Mango
lemons
#    Python 3 program for
#    Find common words in two strings
class Similarity :
	def commonWords(self, str1, str2) :
		record = dict()
		#  Assume that  string contains valid words
		str1Words = str1.split(" ")
		str2Words = str2.split(" ")
		if (len(str1Words) == 0 or len(str2Words) == 0) :
			#  One string is empty
			return
		
		i = 0
		while (i < len(str1Words)) :
			if (not(str1Words[i] in record.keys())) :
				#  Here false are indicates this word exist in first string
				record[str1Words[i]] = False
			
			i += 1
		
		i = 0
		while (i < len(str2Words)) :
			if ((str2Words[i] in record.keys())) :
				#  Here true are indicates this word exist in both string
				record[str2Words[i]] = True
			
			i += 1
		
		for key, value in record.items() :
			if (value) :
				print(key)
			
		
	

def main() :
	task = Similarity()
	#  Input strings
	str1 = "Test Mango orange pineapple and lemons"
	str2 = "Mango is sweet but lemons are sour Test"
	task.commonWords(str1, str2)

if __name__ == "__main__": main()

Output

Mango
lemons
Test
#    Ruby program for
#    Find common words in two strings
class Similarity 
	def commonWords(str1, str2) 
		record = Hash.new()
		#  Assume that  string contains valid words
		str1Words = str1.split(" ")
		str2Words = str2.split(" ")
		if (str1Words.length == 0 || str2Words.length == 0) 
			#  One string is empty
			return
		end

		i = 0
		while (i < str1Words.length) 
			if (!record.key?(str1Words[i])) 
				#  Here false are indicates this word exist in first string
				record[str1Words[i]] = false
			end

			i += 1
		end

		i = 0
		while (i < str2Words.length) 
			if (record.key?(str2Words[i])) 
				#  Here true are indicates this word exist in both string
				record[str2Words[i]] = true
			end

			i += 1
		end

		record.each { | key, value |
			if (value) 
				print(key, "\n")
			end

		}
	end

end

def main() 
	task = Similarity.new()
	#  Input strings
	str1 = "Test Mango orange pineapple and lemons"
	str2 = "Mango is sweet but lemons are sour Test"
	task.commonWords(str1, str2)
end

main()

Output

Test
Mango
lemons
import scala.collection.mutable._;
/*
    Scala program for
    Find common words in two strings
*/
class Similarity()
{
	def commonWords(str1: String, str2: String): Unit = {
		var record: HashMap[String, Boolean] = 
          new HashMap[String, Boolean]();
		// Assume that  string contains valid words
		var str1Words: Array[String] = str1.split(" ");
		var str2Words: Array[String] = str2.split(" ");
		if (str1Words.length == 0 || str2Words.length == 0)
		{
			// One string is empty
			return;
		}
		var i: Int = 0;
		while (i < str1Words.length)
		{
			if (!record.contains(str1Words(i)))
			{
				// Here false are indicates this word exist in first string
				record.addOne(str1Words(i), false);
			}
			i += 1;
		}
		i = 0;
		while (i < str2Words.length)
		{
			if (record.contains(str2Words(i)))
			{
				// Here true are indicates this word exist in both string
				record.addOne(str2Words(i), true);
			}
			i += 1;
		}
		for ((key, value) <- record)
		{
			if (value)
			{
				println(key);
			}
		}
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var task: Similarity = new Similarity();
		// Input strings
		var str1: String = "Test Mango orange pineapple and lemons";
		var str2: String = "Mango is sweet but lemons are sour Test";
		task.commonWords(str1, str2);
	}
}

Output

Test
Mango
lemons
import Foundation;
/*
    Swift 4 program for
    Find common words in two strings
*/
class Similarity
{
	func commonWords(_ str1: String, _ str2: String)
	{
		var record: [String : Bool] = [String: Bool]();
		// Assume that  string contains valid words
		let str1Words: [String] = str1.split
		{
			$0 == " "
		}.map(String.init);
		let str2Words: [String] = str2.split
		{
			$0 == " "
		}.map(String.init);
		if (str1Words.count == 0 || str2Words.count == 0)
		{
			// One string is empty
			return;
		}
		var i: Int = 0;
		while (i < str1Words.count)
		{
			if (!record.keys.contains(str1Words[i]))
			{
				// Here false are indicates this word exist in first string
				record[str1Words[i]] = false;
			}
			i += 1;
		}
		i = 0;
		while (i < str2Words.count)
		{
			if (record.keys.contains(str2Words[i]))
			{
				// Here true are indicates this word exist in both string
				record[str2Words[i]] = true;
			}
			i += 1;
		}
		for (key, value) in record
		{
			if (value)
			{
				print(key);
			}
		}
	}
}
func main()
{
	let task: Similarity = Similarity();
	// Input strings
	let str1: String = "Test Mango orange pineapple and lemons";
	let str2: String = "Mango is sweet but lemons are sour Test";
	task.commonWords(str1, str2);
}
main();

Output

Mango
Test
lemons
/*
    Kotlin program for
    Find common words in two strings
*/
class Similarity
{
	fun commonWords(str1: String, str2: String): Unit
	{
		val record = hashMapOf < String, Boolean > ();
		// Assume that  string contains valid words
		val str1Words: List < String > = str1.split(" ");
		val str2Words: List < String > = str2.split(" ");
		if (str1Words.count() == 0 || str2Words.count() == 0)
		{
			// One string is empty
			return;
		}
		var i: Int = 0;
		while (i < str1Words.count())
		{
			if (!record.containsKey(str1Words[i]))
			{
				// Here false are indicates this word exist in first string
				record.put(str1Words[i], false);
			}
			i += 1;
		}
		i = 0;
		while (i < str2Words.count())
		{
			if (record.containsKey(str2Words[i]))
			{
				// Here true are indicates this word exist in both string
				record.put(str2Words[i], true);
			}
			i += 1;
		}
		for ((key, value) in record)
		{
			if (value)
			{
				println(key);
			}
		}
	}
}
fun main(args: Array < String > ): Unit
{
	val task: Similarity = Similarity();
	// Input strings
	val str1: String = "Test Mango orange pineapple and lemons";
	val str2: String = "Mango is sweet but lemons are sour Test";
	task.commonWords(str1, str2);
}

Output

Test
Mango
lemons




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment