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?

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

Prem

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?

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

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! ;-)

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.

Then mark as solved

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.