Split Method in Java
Date: Oct 2014
Level: Intermediate


INTERVIEW QUESTIONS

Question Title: Split Method in Java
Language: Java
QUESTION DETAILS:

How to implement split () method in Java?


Here's one example. This will produce the following output:

--
--Here is some text
-- which is
-- not making
-- any
-- sense
--
import java.util.*;
public class Fonts {
	public static void main(String[] args) {
		String inputString = ",Here is some text, which is, not making, any, sense,";
		//String[] output = split(inputString, ',');
		String[] output = splitMine(inputString, ',');
		for (int i = 0; i < output.length; i++) {
			System.out.println("--"+output[i]);
		}
	}
	public final static String[] splitMine(String str, char separatorChar) {
		if (str == null) {
			return null;
		}
		int len = str.length();
		if (len == 0) {
			return null;
		}
		List<String> list = new ArrayList<String>();
		int temp =0;
		int fromIndex = 0;
		while (temp>=0){
			temp = str.indexOf(separatorChar,fromIndex);
			if(temp<0){
				list.add(str.substring(fromIndex,len));
				break;
			}else{
				list.add(str.substring(fromIndex,temp));
			}
			fromIndex = temp+1;
		}
		String[] arr = new String[list.size()];
		list.toArray(arr);
		return arr;
	}
}
All Questions