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?

5
Contributors
6
Replies
7
Views
6 Years
Discussion Span
Last Post by rapture
Featured Replies
  • 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 … Read More

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.