This example describes how replace method of java String class can be used to replace character or substring by new one.
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") );
}
}
Result
The above code sample will produce the following result.
Wello World
Wallo World
Hallo World
Showing posts with label substring. Show all posts
Showing posts with label substring. Show all posts
How to search the last position of a substring ?
This example shows how to determine the last position of a substring inside a string with the help of strOrig.lastIndexOf(Stringname) method.
public class SearchlastString {
public static void main(String[] args) {
String strOrig = "Hello world ,Hello Reader";
int lastIndex = strOrig.lastIndexOf("Hello");
if(lastIndex == - 1){
System.out.println("Hello not found");
} else {
System.out.println("Last occurrence of Hello is at index "+ lastIndex);
}
}
}
Result
The above code sample will produce the following result.
Last occurrence of Hello is at index 13
Example
This another example shows how to determine the last position of a substring inside a string with the help of strOrig.lastIndexOf(Stringname) method.
public class HelloWorld{
public static void main(String []args) {
String t1 = "Tutorialspoint";
int index = t1.lastIndexOf("p");
System.out.println(index);
}
}
The above code sample will produce the following result.
9
public class SearchlastString {
public static void main(String[] args) {
String strOrig = "Hello world ,Hello Reader";
int lastIndex = strOrig.lastIndexOf("Hello");
if(lastIndex == - 1){
System.out.println("Hello not found");
} else {
System.out.println("Last occurrence of Hello is at index "+ lastIndex);
}
}
}
Result
The above code sample will produce the following result.
Last occurrence of Hello is at index 13
Example
This another example shows how to determine the last position of a substring inside a string with the help of strOrig.lastIndexOf(Stringname) method.
public class HelloWorld{
public static void main(String []args) {
String t1 = "Tutorialspoint";
int index = t1.lastIndexOf("p");
System.out.println(index);
}
}
The above code sample will produce the following result.
9
Subscribe to:
Posts (Atom)