Sometimes it is very important to split a string on a comma n t etc. This piece of code will help you with it.
import java.util.*; public class split{ public static void main ( String args[]) { // this is my string String s = "Java, Programming is ,,, fun do you agree? ."; split String regexp = "[\s,;\n\t]+"; // these are my delimiters String [] tokens; // here i will save tokens // length is 7 because i know that my string will consist of 7 tokens for(int i=0;i<7;i++){ tokens = s.split(regexp); System.out.println(tokens[i]); } } } // tokens are: Java Programming is fun do you agree?
Check out more posts on “Useful Java Functions and Tutorials”
Thanks for installing the Bottom of every post plugin by Corey Salzano. Contact me if you need custom WordPress plugins or website design.
>> // length is 7 because i know that my string will consist of 7 tokens
We never know =)
You are absolutely right, that’s why this function can be easily upgraded and “7” replaced by the variable, or for loop can be easily replaced by foreach loop. However, in my case i know how many tokes I have 🙂
Yeah Yeah 🙂
use Apache Commons StringUtils.split(String text, String delimeters) dude and dont build own bicycle
b2b thanks for sharing !
I don’t think that creating 18-line function is reinventing the wheel, its purpose is to show alternative way of solving the current problem.
This function can be customized for any language that accepts regular expressions, unfortunately StringUtils is language-limited.
you need to move the line that calls split outside the for loop. As it is you split the line 7 times, when you only need to do it once.