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

Related Posts:

  • Method References in Java8 Method References: Method references refers to methods or constructors without invoking them. We can use lambda expressions to create anonymous methods.  Sometimes, however, a lambda expression d… Read More
  • 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 b… Read More
  • Spring MVC Hello World ExampleIn this post, we are going to see how to implement Spring MVC HelloWorld example.Step 1:The initial step is to create Dynamic Web Project in eclipse. To create a new Dynamic project in Eclipse IDE select File -> Dynamic We… Read More
  • Top 8 Java People you should knowTop 8 Java People You Should KnowHere are the top 8 Java people, they’re created frameworks, products, tools or books that contributed to the Java community, and changed the way of coding Java.1. Father of the Java programmin… Read More
  • Java8 New Features New Features of Java 8: The following are the major features of Java 8: Lambda Expressions Method References Functional Interfaces (java.util.function) Default and Static Methods The Stream API (java.util.strea… Read More

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));