1.11M Members

Replace method Strings

 
0
 

I'm trying to write a program that switches the "x" and "o" in a String, only using the replace method repeatedly.

At the end of the day, the program should turn 'xxxooo' into 'oooxxx'.

I understand why this isn't working, but I'm just completely out of ideas as to how to make it work. So here's what I have:

firstStep = console.nextLine();
secondStep = firstStep.replaceAll(o, x);
thirdStep = thirdStep.replace(x, o);
System.out.println(thirdStep);

Is there a way to accomplish this replacement in one step?

 
0
 

kindly display your program so that it will me more clear to understand.

Prem

 
1
 

Actually, that won't work, anyway. As if you replace all o with x then all x with o your string will consist of nothing but o

Step 1: get string
Step 2: replace x with z
Step 3: replace o with x
Step 4: replace z with o

Why do you feel the need to do it in one?

 
0
 

Even at the pseudocode level that's not going to work:
firstStep = console.nextLine(); eg "ooxxx"
secondStep = firstStep.replaceAll(o, x); "xxxxx"
thirdStep = thirdStep.replace(x, o); "ooooo"
System.out.println(thirdStep); "ooooo"

This needs an extra step:
replace all the o with some temp char
replace all the x with o
replace all the temp char with x

 
0
 

Even at the pseudocode level that's not going to work:
firstStep = console.nextLine(); eg "ooxxx"
secondStep = firstStep.replaceAll(o, x); "xxxxx"
thirdStep = thirdStep.replace(x, o); "ooooo"
System.out.println(thirdStep); "ooooo"

This needs an extra step:
replace all the o with some temp char
replace all the x with o
replace all the temp char with x

Too slow! ;-)

 
0
 

Actually, that won't work, anyway. As if you replace all o with x then all x with o your string will consist of nothing but o

Step 1: get string
Step 2: replace x with z
Step 3: replace o with x
Step 4: replace z with o

Why do you feel the need to do it in one?

Thank you so much, when I woke up this morning my brain had also determined this path and I got it working! I appreciate your help.

 
0
 

Then mark as solved

Question Answered as of 3 Years Ago by masijade, rapture, JamesCherrill and 1 other
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: