2009年3月2日 星期一

Lab String Processing

Do Project 5 of Chap. 1 on Page 56.

Write a program that starts with a line of text and then outputs that line of text with the first occurrence of "hate" changed to "love". For example, a possible sample output might be

The line of text to be changed is:
I hate you.
I have rephrased that line to read:
I love you.

Hint: You may consider use the methods: indexOf(A_String) and substring(Start, End) in your program.

------------------------------------------------<程式碼開始>--------------------------------------

public class hanyi
{
public static void main( String[] args )
{
String sentence = "I hate you.";
int position = sentence.indexOf("hate");
String ending = sentence.substring(position + "hate".length());
System.out.println( sentence );
System.out.println( "hate -> love" );
sentence = sentence.substring(0, position) + "love" + ending;
System.out.println( sentence );
}
}
------------------------------------------------<程式碼結束>--------------------------------------

沒有留言:

張貼留言