Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Split the string by given character using indexOf method in Java

Write a method that takes a String and a character as arguments, and split the string by given character using String indexOf method.

 

Signature

public static Listsplit(String data, int ch)

 

we can implement split method using indexOf, substring methods of String class.

 

public int indexOf(int ch, int fromIndex)

Returns the index of the first occurrence of the character in the character sequence represented by this object that is greater than or equal to fromIndex, or -1 if the character does not occur.

 

public String substring(int beginIndex)

Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

 

public String substring(int beginIndex, int endIndex)

Returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

 

Definition of split method is given below.

public static Listsplit(String data, int ch) {
	List splits = new ArrayList();
	int currentPosition = -1;
	int fromIndex = 0;
	while ((currentPosition = data.indexOf(ch, fromIndex)) != -1) {
		splits.add(data.substring(fromIndex, currentPosition));
		fromIndex = currentPosition + 1;
	}
	splits.add(data.substring(fromIndex));
	return splits;
}

 


Find the below working application.

 

StringSplitDemo.java
package com.sample.app.strings;

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

public class StringSplitDemo {

	public static Listsplit(String data, int ch) {
		List splits = new ArrayList();
		int currentPosition = -1;
		int fromIndex = 0;
		while ((currentPosition = data.indexOf(ch, fromIndex)) != -1) {
			splits.add(data.substring(fromIndex, currentPosition));
			fromIndex = currentPosition + 1;
		}
		splits.add(data.substring(fromIndex));
		return splits;
	}

	public static void main(String[] args) {
		String str = "Hello, are you there";

		List splits = split(str, ' ');
		for (String split : splits) {
			System.out.println(split);
		}

	}
}

 

Output

Hello,
are
you
there

 

  

Previous                                                 Next                                                 Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Split the string by given character using indexOf method in Java

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×