Tuesday 2 May 2023

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 List<String> split(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 List<String> split(String data, int ch) {
	List<String> 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 List<String> split(String data, int ch) {
		List<String> 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<String> splits = split(str, ' ');
		for (String split : splits) {
			System.out.println(split);
		}

	}
}

 

Output

Hello,
are
you
there

 

  

Previous                                                 Next                                                 Home

No comments:

Post a Comment