Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Examples – String Replacement

Java Example – String replacement

Java Examples Java Examples

How do you replace characters in a string with Java?

In the following example we use the replace method of the Java String class to replace characters in a string:

StringReplaceEmp.java file

public

class

StringReplaceEmp

{

public

static

void

main

(

String

args

[

]

)

{

String

str

=

"

Hello World

"

;

System

.

out

.

println

(

str

.

replace

(

'

H

'

,

'

W

'

)

)

;

System

.

out

.

println

(

str

.

replaceFirst

(

"

He

"

,

"

Wa

"

)

)

;

System

.

out

.

println

(

str

.

replaceAll

(

"

He

"

,

"

Ha

"

)

)

;

}

}

The output of the above code example is:


Wello World
Wallo World
Hallo World

Java Examples Java Examples