Oh, I looked at this several ways. I hesitate to give you my code because your instructor will know you didn't do it. But, here it is. You will note I look for the e's and record the numeric positions. I then change the o's. I take the new String with the o's, make a StringBuffer. With my numeric positions, I change the e's to o's. I then change the StringBuffer back to a String.
I couldn't never do a double-pass using .replace('e','o'); .replace('o','e'). Using subsequence turns into a mudball.
==============
import java.util.Scanner;
/**
* Created on Sep 8, 2008, 7:44:25 PM
*
* @author vjuan
*/
public class StringSwapChar {
// the constructor of the class
public StringSwapChar() {
// when a new class Object is created, do the method
intro();
}
public static void main( String[] args ) {
// one gets state, values, methods() with an Object
// the keyword 'new' makes an Object into memory
new StringSwapChar();
// most of the time you see a 'label' attached to
// manfacture a var label. I could do so...
// StringSwapChart ssc = new StringSwapChart();
// but then, I'd have to access everything like this
// ssc.run ... or ssc.swapOE( ssc.s )
}
// methods
private String swapOE( String s ) {
String ndexes = "";
for (int i = 0; i < s.length(); i++) {
int c = Integer.valueOf(s.charAt(i));
int ee = Integer.valueOf('e');
ndexes += (c == ee ) ? String.valueOf(i)+"," : "";
}
ndexes =
ndexes.substring(
0,ndexes.lastIndexOf(","));
// mess(ndexes+"\n");
String newSe = s.replace('o', 'e');
String newSo = swapEO( newSe, ndexes );
return newSo;
}
private String swapEO( String s, String dex ) {
String[] ndexes = dex.split(",");
StringBuffer sb = new StringBuffer(s);
for (int i = 0; i < ndexes.length; i++) {
sb.setCharAt( Integer.valueOf(ndexes[i]) , 'o');
}
String newString = sb.toString();
return newString;
}
private void mess( String s ) {
System.out.print( s );
}
private boolean ending( Scanner scanner ) {
boolean keepGoing = true;
System.out.print("Enter another String? ");
keepGoing =
scanner.nextLine().
equalsIgnoreCase("y");
if( !keepGoing ) {
// if false print bye bye
mess("Bye! User typed \"N\"\n");
}
else
mess("User typed \"Y\"\n\n");
return keepGoing;
}
private void intro() {
boolean run = true;
Scanner sc = new Scanner( System.in );
while( run ) {
mess("Input a String: ");
String input = sc.nextLine();
mess( swapOE(input) + "\n" );
run = ending(sc);
}
}
}
////////////////
if there was a shorter way without using RegEx, I'd like to see the code
good luck