Java String split
Split is one of the most use methods of Java String to split a string to match a certain regular expression. Observe the following example:
package net.searchdaily.java.string.common;
/**
* This is an indepth-example of Java String to demonstrate all features of this
* class. http://java.searchdaily.net. *
*
* @author namnvhue
*
*/
public class StringSplitExample {
public static void main(String args[]) {
/* String to split. */
String str = "java-string-to-split";
String[] tempString;
// delimiter
String delimiter = "-";
// given string will be split.
tempString = str.split(delimiter);
// print the result
for (int i = 0; i < tempString.length; i++)
System.out.println(tempString[i]);
/*
* ATTENTION : Some special characters need to be escaped while
* providing them as delimiters like "." and "|".
*/
System.out.println("");
str = "java.string.to.split";
delimiter = ".";
tempString = str.split(delimiter);
for (int i = 0; i < tempString.length; i++)
System.out.println(tempString[i]);
// The second parameter of the split method can help to determine the
// number of maximum elements to split.
System.out.println("");
tempString = str.split(delimiter, 3);
for (int i = 0; i < tempString.length; i++)
System.out.println(tempString[i]);
}
}
As you can guess, here is the final result:
Java String to Int
There are several ways to convert from a String to Integer, the first and most use is to use Integer.parseInt() method from the Integer class.
package net.searchdaily.java.string.common;
/**
* Convert Java String into Integer. http://java.searchdaily.net. *
*
* @author namnvhue
*
*/
public class StringToInt {
public static void main(String[] args) {
String stringText = "2011";
int intVar = 0;
try {
intVar = Integer.parseInt(stringText);
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}
// now do some integer operation
intVar++;
System.out.println(intVar);
}
}
Yes the result of the above conversion is 2012, but please remember to catch the exception because the parseInt() method will throw some NumberFormatException if the stringText is not a well-numeric-format.