Interview Question
Java DevelopersCountry: United States
public final static String[] split( String str, char separatorChar ) {
if ( str == null ) {
return null;
}
int len = str.length();
if ( len == 0 ) {
return null;
}
Vector list = new Vector();
int i = 0;
int start = 0;
boolean match = false;
while ( i < len ) {
if ( str.charAt( i ) == separatorChar ) {
if ( match ) {
list.addElement( str.substring( start, i ).trim() );
match = false;
}
start = ++i;
continue;
}
match = true;
i++;
}
if ( match ) {
list.addElement( str.substring( start, i ).trim() );
}
String[] arr = new String[list.size()];
list.copyInto( arr );
return arr;
}
public class Split {
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;
}
}
public final static String[] split( String str, char separatorChar ) {
- Anonymous October 18, 2014if ( str == null ) {
return null;
}
int len = str.length();
if ( len == 0 ) {
return null;
}
Vector list = new Vector();
int i = 0;
int start = 0;
boolean match = false;
while ( i < len ) {
if ( str.charAt( i ) == separatorChar ) {
if ( match ) {
list.addElement( str.substring( start, i ).trim() );
match = false;
}
start = ++i;
continue;
}
match = true;
i++;
}
if ( match ) {
list.addElement( str.substring( start, i ).trim() );
}
String[] arr = new String[list.size()];
list.copyInto( arr );
return arr;
}