Friday 12 February 2016

Basic string manipulation in Java with Real Examples : Part 1

Hi guys, how you doing today? I just noticed I haven't written anything about Java in quite some time now. Well let's bring Java back into the spotlight with this light subject on basic string manipulation.

Lets try to cover some simple examples covering different scenarios :

Illustration 1 : Extract a substring from a string

In this example we simply extract a part of the string.

public class String_manip {

public static void main(String[] args) {
 String str = "Hello guys. Welcome to IroncladZone";
 
 String sub_str = str.substring(23, 35);
 
 System.out.println (sub_str);
}

}

Output : IroncladZone

Illustration 2 : Replace a substring from a string

In this example we replace the word "guys" with "goodfellas" within the string.

public class String_manip {

public static void main(String[] args) {
String str = "Hello guys. Welcome to IroncladZone";
String replaced_str = str.replace("guys", "goodfellas");
System.out.println(replaced_str);

}

}

Output : Hello goodfellas. Welcome to IroncladZone

Note that strings are immutable. Their value cannot be changed once its created. However we can create a new string with the replaced word/part.

Illustration 3 : Join / Combine two strings i.e Concatenation

In this we simply join 3 strings together using +

public class String_manip {

public static void main(String[] args) {
String str1 = "Welcome";
String str2 = "to";
String str3 = "IroncladZone";
System.out.println(str1 + str2 + str3);
System.out.println(str1 + " " + str2 + " " + str3);

}

}

Output : 
WelcometoIroncladZone
Welcome to IroncladZone

Illustration 4 : Print the length of the string


public class String_manip {

public static void main(String[] args) {
String str = "Welcome to IroncladZone";
System.out.println(str.length());

}

}

Output :
23

Note the length() function used to show the length of the string.

Illustration 5 : Split a string on a whitespace

public class String_manip {

public static void main(String[] args) {
String str = "Welcome to IroncladZone";
String[] new_str = str.split("\\s+");
System.out.println(new_str[0]);

}


}

Output :
Welcome

Notice the \\s+ regex for the whitespace.

That's it for today fellas. I'll try to include some more advanced scenarios in a 2nd part of this post. There's more to come guys, stay tuned...

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...
eXTReMe Tracker