concat(), replace(), and trim() Strings in Java

By: Ivan Lim  

concat()

You can concatenate two strings using concat(), shown here:

String concat(String str)

This method creates a new object that contains the invoking string with the contents of str appended to the end. concat( ) performs the same function as +. For example,

String s1 = "one";
String s2 = s1.concat("two");

puts the string "onetwo" into s2. It generates the same result as the following sequence:

String s1 = "one";
String s2 = s1 + "two";

replace()

The replace( ) method replaces all occurrences of one character in the invoking string with another character. It has the following general form:

String replace(char original, char replacement)

Here, original specifies the character to be replaced by the character specified by replacement. The resulting string is returned. For example,

String s = "Hello".replace('l', 'w');

puts the string "Hewwo" into s.

trim()

The trim( ) method returns a copy of the invoking string from which any leading and trailing whitespace has been removed. It has this general form:

String trim( )

Here is an example:

String s = " Hello World ".trim();

This puts the string "Hello World" into s.

The trim( ) method is quite useful when you process user commands. For example, the following program prompts the user for the name of a state and then displays that state's capital. It uses trim( ) to remove any leading or trailing whitespace that may have inadvertently been entered by the user.

// Using trim() to process commands.
import java.io.*;
class UseTrim {
public static void main(String args[])
throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter 'stop' to quit.");
System.out.println("Enter State: ");
do {
str = br.readLine();
str = str.trim(); // remove whitespace
if(str.equals("Illinois"))
System.out.println("Capital is Springfield.");
else if(str.equals("Missouri"))
System.out.println("Capital is Jefferson City.");
else if(str.equals("California"))
System.out.println("Capital is Sacramento.");
else if(str.equals("Washington"))
System.out.println("Capital is Olympia.");
// ...
} while(!str.equals("stop"));
}
}



Archived Comments

1. JasonNix
View Tutorial          By: JasonNix at 2017-04-25 08:36:35

2. JasonNix
View Tutorial          By: JasonNix at 2017-04-13 02:27:07

3. can apply this code in android
View Tutorial          By: Tech Genus at 2016-05-05 11:29:57

4. how to trim in jsp page and to send the trimed conten to servlet?
View Tutorial          By: monishaa at 2015-07-16 10:06:11

5. Can I ask something,

Can you show me how to use TRIM in GUI

TQ =)

View Tutorial          By: wawa at 2014-05-03 15:28:35

6. one of the best example for trim()....
View Tutorial          By: sharad at 2013-01-29 13:43:58


Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial