previous | start | next

String Example

Replace all i's with the character '1' and all s's with the character '$' in the string "Mississippi".

/**
 * Description: Exercise p2.9. Test string replace method.
 * 
 * @author Glenn Lancaster
 * 
 */
public class ReplaceTester
{

  
  public static void main(String[] args)
  {
    String original = "Mississippi";
    String newstring;
    String expected = "M1$$1$$1pp1";

    newstring = original.replace('i', '1');
    newstring = newstring.replace('s', '$');

    System.out.println("Original String: " + original);
    System.out.println("Replaced String: " + newstring);
    System.out.println("       Expected: " + expected);
  }
}

Note that the + operator with String operands is overloaded to mean concatenation of strings.



previous | start | next