String in Java


StringTokenizer 

This is used to split a string based on a delimiter. The delimiter for example can be a comma  or space (space is the default delimiter)

The following is a java code snippet that takes a String of email addresses delimited by comma, separates them and stores into a ArrayList
String emailAddresses = "abc@123.com, xyz@123.com";

List emailAddressList = new ArrayList();

StringTokenizer st = new StringTokenizer(emailAddresses, ",");
    while (st.hasMoreTokens()) {
        emailAddressList.add(st.nextElement().toString());
}


Converting ArrayList to String Array

The following is a sample java code that demonstrates the ArrayList to String Array conversion

String[] ccEmail = new String [10];
List emailAddressList = new ArrayList();
ccEmail = emailAddressList.toArray(new String[emailAddressList.size()]);   

Getting Substrings from a String

String str = "How are you";
// To identify the above string with 'startsWith' method
boolean  present = str.startsWith("How");  
// To identify the above string with 'endsWith' method
present = str.endsWith("you");             
// Anywhere
present = str.indexOf("re y") > 0;        
// To ignore case, regular expressions must be used // Starts with present = str.matches("(?i)how.*"); // Ends with present = str.matches("(?i).*you"); // Anywhere present = str.matches("(?i).*re y.*");


split(String regex)

This method is used to split strings based on a regular expression.

public static void main (String args[]){
   String str = "Hello how are you";
   for (String s: str.split(" ")){
        System.out.println("--");
   }
}

Output :
Hello--how--are--you--

It splits the string based on space.


No comments:

 Python Basics How to check the version of Python interpreter mac terminal

Popular in last 30 days