Click here to Skip to main content
15,896,437 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
See more:
Hi,
I need to write a program that takes two strings from the user and checks for the common chars in string1 and string2 without repeating the same char twice..
for example:

first_string: "4*3minus5is7"
second_string: "1*+-12345ijklmn"
The result string is:"4*3mn5i"

please HELP
Posted

This smells a lot like homework, so I am not going to give you code!
However, it's not a complex task, all you have to do is think about it for a bit.

Rule one when trying to do anything like this: "Sort your strings".

Then it becomes easy:

You need a loop, and a couple of comparisons.
Set up two indexes, one into each string, and zero them both.
In the loop, compare the two characters at the relevant indexes.
If the character in string 1 is less than the character in string 2, advance the index to string 1. If this takes it out of string one, you need all the characters of string 2, and you are done. Otherwise if the character at the next position is the same, keep advancing (this is to skip duplicates)
If the two characters are the same, add it to the output, and advance both pointers. If either has run out of string, you need all the characters from the other, and you are done.
If the character in string 1 is greater than the character in string 2, advance the index to string 2. Check for end of string, output string 1 if so. Don't forget the duplicates!
Repeat!

The code is probably shorter than the description!
 
Share this answer
 
read string1
read string2
remove all duplicates from string1
for each character in string1
    if character exists in string2
    then
        print character
end for
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900