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:

  • CRUD Operations Using HibernateBelow example explains how to perform Create, Read, Update and Delete (CRUD) operations using Hibernate.Tools: Eclipse,MySQLHiberante 4.3.6Project Structure:Step1: Creating the POJO classEmployee.javapackage com.var… Read More
  • Creating our Own Hibernate Template classLet us see how to develop our own Hibernate Template class.HibernateTemplate.javaimport java.io.Serializable;import java.util.List;import org.hibernate.HibernateException;import org.hibernate.Query;import org.hibernate.Sessio… Read More
  • Explain about Hibernate Object Life Cycle?In hibernate object life cycle, mainly consists of four states. They are Transient State, Persistent State, Detached State and Removed State.Hibernate Object Life Cycle1. New or Transient State:When ever a… Read More
  • Hibernate Object Identity and EqualityThere are several mismatches between the Object oriented system and Relation system. In that one of the important mismatch is Object identity and equality.There are three ways to tackle identity: two ways in java world, and o… Read More
  • Creating Custom Generator class in HibernateIn this post, we are going to learn how to create custom generator class in hibernate.Hibernate supports many built in generator classes like assigned, sequence, increment, identity, native etc. But some requirements the… 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));