Friday, September 14, 2012

Spliting a String without using any built in functions in Java

In this post, we are going to see how to split a string without using any built in functions.
package com.ranga;

import java.util.ArrayList;
import java.util.List;

/**
* Write a Java program to split a string with out using any bulit methods like
* split(), StringTokenizer class methods.
*
* @author Ranga Reddy
* @version 1.0
*/

public class SplitString {
public static void main(String[] args) {
String str = "Welcome to JavabyRangaReddy blog";
String delimiter = " "; // here delimiter is space
List<String> list = new ArrayList<String>(); // list is used to store the words
int i, start = 0, end = 0;
for (i = str.indexOf(delimiter); i != -1; i = str.indexOf(delimiter, i + 1)) {
end = i;
list.add(str.substring(start, end)); // by using substring we can get the one word
start = i;
}
list.add(str.substring(end)); // this is used to add the last word
System.out.println(list); // print the list

// Converting list to array of strings
String words[] = (String[]) list.toArray(new String[list.size()]);
for (String word : words) {
System.out.println(word.trim());
}
}
}
Output:
[Welcome,  to,  JavabyRangaReddy,  blog]
Welcome
to
JavabyRangaReddy
blog

1 comments:

Ankita said...

Hey!

Thank you for the above code.

There is one suggestion, instead of using trim() you can just put i+1 in start .
start=i+1;

list.add(str.substring(end+1));