954,173 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

replace characters in array

hey guys , i am trying to write this program , the program has 3 arrays
char source[]="abcdefghijklmnopqrstuvwxyz";
char target[]="jfghdfsdyncdbdfklhdslasudfds";
char line[26];
now i have to ask the user to enter a line
cin.getline(line,26)
what i want to do is to check the characters in the user input(line) if it exist in the source array.and then replace each characters with the corresponding one from target array.for example if user enter the word "dad", the program have to check for d,a,d in the source and replace them with the corresponding one from target in this case the output will be djd. any ideas i would really appreciated.

azagorath
Newbie Poster
3 posts since Dec 2008
Reputation Points: 10
Solved Threads: 0
 

Simple, for each character in the line array, search through the source array for the character, then use the same index to replace the characters with that of the target array...You'll most likely want to use two for-loops.

nmaillet
Posting Whiz in Training
225 posts since Aug 2008
Reputation Points: 69
Solved Threads: 53
 

two for loops will not be necessary, a single one would do,

for each character in the input string,
substitute with target[char - 'a']

since u are going to have one to one correspondence, the requirement of source array is nill

geekru2
Newbie Poster
3 posts since Dec 2008
Reputation Points: 10
Solved Threads: 0
 

i was trying to use strcmp to compare string char between line and source but i still stuck in the replacment part

azagorath
Newbie Poster
3 posts since Dec 2008
Reputation Points: 10
Solved Threads: 0
 

Assuming that you have a source array that isn't abc... then you want to do it with one + one loop. I don't know why you read only 26 characters from the keyboard line. What if I have a long sentence ...
If you have a loop in a loop say for an input of 500 charaters and 26 letters, then you have 500*26/2 as the number of operations (assuming you find the letter you are after in 13 tries on average).
That is a huge overhead

So you create a mapping of a->? and b->? in another array and then
pass your input line.

You will need to get the correct look up for the array carefully done

outputLetter = newTarget[inputLetter-'a'];


Some care will also be needed on the issue of capitals and non- alphabet input, etc.

StuXYZ
Practically a Master Poster
680 posts since Nov 2008
Reputation Points: 760
Solved Threads: 138
 

the reason i made it 26 letters is just for testing the code , once i get my code right i can make the input bigger.

azagorath
Newbie Poster
3 posts since Dec 2008
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You