Java assignment 04: Working with strings

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
Java Assignments   Green = Easy,  Blue = Normal,  Red = Hard
Select    01   02   03   04   05   06   07   08   09   10   By title 

As a Java programmer you will often need to work with the Java standard API specification. I tried to write a Java assignment based on one of my favorite quotes.

The text of the q is a quote by Mahatma Gandhi, but there is an unwanted web site link inside the quote.
Write only one statement on the line 8 to remove that link from the quote. As the result of that the program writes the quote correctly to the standard output as follows:
“Be the change you wish to see in the world.” 

Hint: Search the class String and read what you can do with the method replaceAll in the Java standard API specification.

Java assignment 4: Working with the class String

Level: Normal

public class HandlingText
{
  public static void main(String[] args)
  {
    String quote = "";
    String q = "Be the change you "
        + "link.com" +
        " wish to see in the world.";
    // add your statement here!
    System.out.print(quote);
  }
}
 Author: Sar Maroof

 

Answer explanation

You can use the method replaceAll.
Remember that by programming there might be many ways to achieve a specific goal.
The statement is: quote = q.replaceAll(“link.com “, “”);. The website link will be replaced by nothig or it will be simply removed. Open the Java standard API specification. again, try to find the method replaceAll(String regex, String replacement) and read more info about what you can do with that method and other methods inside the String class.

 

public class HandlingText
{
  public static void main(String[] args)
  {
    String quote = "";
    String q = "Be the change you "
        + "link.com" +
        " wish to see in the world.";
    quote = q.replaceAll("link.com ", "");
    System.out.print(quote);
  }
}

 





Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *