How can I split a string into words in Java without using String.split ()?

My teacher specifically asked to divide the sentence into words, without using String.split(). I did this using Vector(which we have not yet learned), while-loop and substrings. What are other ways to achieve this? (preferably without using Vectors/ ArrayLists).

+5
source share
15 answers

I believe that your teacher asks you to process the string yourself (without using any other libraries for this). Make sure this is so - if you can use them, there are things like StringTokenizer, Pattern, and Scanner to simplify string processing.

Otherwise...

(, , , ..), , , . ( ) ( ), reset , .

+14

, , . , .

+4

java.util.Scanner.

+2

java.util.StringTokenizer, , . SPACE/TAB/NEW_LINE.

String myTextToBeSplit = "This is the text to be split into words.";  
StringTokenizer tokenizer = new StringTokenizer( myTextToBeSplit );  
while ( tokinizer.hasMoreTokens()) {  
    String word = tokinizer.nextToken();  
    System.out.println( word ); // word you are looking in  
}  

java.util.Scanner

Scanner s = new Scanner(myTextToBeSplit).useDelimiter("\\s");  
while( s.hasNext() ) {  
System.out.println(s.next());  
}  
s.close();  
+2
import java.util.Arrays;
public class ReverseTheWords {

    public static void main(String[] args) {
        String s = "hello java how do you do";
        System.out.println(Arrays.toString(ReverseTheWords.split(s)));
    }

    public static String[] split(String s) {
        int count = 0;
        char[] c = s.toCharArray();

        for (int i = 0; i < c.length; i++) {
            if (c[i] == ' ') {
                count++;
            }
        }
        String temp = "";
        int k = 0;
        String[] rev = new String[count + 1];
        for (int i = 0; i < c.length; i++) {
            if (c[i] == ' ') {
                rev[k++] = temp;
                temp = "";
            } else
                temp = temp + c[i];
        }
        rev[k] = temp;
        return rev;
    }

}
+2

Pattern ( ), .

+1
  • ctor (String)
  • StringTokenizer
  • char char
+1

Vector/List ( ) , N (N+1)/2 ( ). , , , Vector, .

:

String[] mySplit( String in ){
    String[] bigArray = new String[ (in.length()+1)/2 ];

    int numWords = 0;
    // Populate bigArray with your while loop and keep
    // track of the number of words

    String[] result = new String[numWords];
    // Copy results from bigArray to result

    return result;
}
+1
public class MySplit {

public static String[] mySplit(String text,String delemeter){
    java.util.List<String> parts = new java.util.ArrayList<String>();
    text+=delemeter;        

    for (int i = text.indexOf(delemeter), j=0; i != -1;) {
        parts.add(text.substring(j,i));
        j=i+delemeter.length();
        i = text.indexOf(delemeter,j);
    }


    return parts.toArray(new String[0]);
}

public static void main(String[] args) {
    String str="012ab567ab0123ab";
    String delemeter="ab";
    String result[]=mySplit(str,delemeter);
    for(String s:result)
        System.out.println(s);
}

}
+1
public class sha1 {
public static void main(String[] args) {
    String s = "hello java how do you do";
    System.out.println(Arrays.toString(sha1.split(s)));
}
public static String[] split(String s) {
    int count = 0;
    char[] c = s.toCharArray();

    for (int i = 0; i < c.length; i++) {
        if (c[i] == ' ') {
            count++;
        }
    }
    String temp = "";
    int k = 0;
    String[] rev = new String[count + 1];
    for (int i = c.length-1; i >= 0; i--) {
        if (c[i] == ' ') {
            rev[k++] = temp;
            temp = "";
        } else
            temp = temp + c[i];
    }
    rev[k] = temp;
    return rev;
}

}

+1

! , .

com.asif.test;

SplitWithoutSplitMethod {

public static void main(String[] args) {

    split('@',"asif@is@handsome");
}

static void split(char delimeter, String line){

    String word = "";
    String wordsArr[] = new String[3];

    int k = 0;
    for(int i = 0; i <line.length(); i++){

        if(line.charAt(i) != delimeter){
            word+= line.charAt(i);
        }else{
            wordsArr[k] = word;
            word = "";
            k++;                    
        }
    }
    wordsArr[k] = word;
    for(int j = 0; j <wordsArr.length; j++)
    System.out.println(wordsArr[j]);

}

}

+1

, .

  public static String[] mysplit(String mystring) {

    String string=mystring+" ";               //append " " bcz java string does not hava any ending character
    int[] spacetracker=new int[string.length()];// to count no. of spaces in string
    char[] array=new char[string.length()];     //store all non space character
    String[] tokenArray=new String[string.length()];//to return token of words

    int spaceIndex=0;
    int parseIndex=0;
    int arrayIndex=0;
    int k=0;
    while(parseIndex<string.length())
    {
        if(string.charAt(parseIndex)==' '||string.charAt(parseIndex)==' ')
        {
            spacetracker[spaceIndex]=parseIndex;
            spaceIndex++;
            parseIndex++;
        }else
        {
        array[arrayIndex]=string.charAt(parseIndex);
        arrayIndex++;
        parseIndex++;
        }
    }


    for(int i=0;i<spacetracker.length;i++)
    {
        String token="";
        for(int j=k;j<(spacetracker[i])-i;j++)
        {
            token=token+array[j];
            k++;

        }
        tokenArray[i]=token;
        //System.out.println(token);
        token="";

    }
    return tokenArray;
}

,

0
import java.util.*;
class StringSplit {
    public static void main(String[] args) 
    {
        String s="splitting a string without using split()";
        ArrayList<Integer> al=new ArrayList<Integer>();     //Instead you can also use a String 
        ArrayList<String> splitResult=new ArrayList<String>();
        for(int i=0;i<s.length();i++)
            if(s.charAt(i)==' ')
                al.add(i);
        al.add(0, 0);
        al.add(al.size(),s.length());
        String[] words=new String[al.size()];
        for(int j=0;j<=words.length-2;j++)
                splitResult.add(s.substring(al.get(j),al.get(j+1)).trim());
        System.out.println(splitResult);
    }
}

: O (n)

0
source

You can also use String.substringor charAt[].

-3
source

All Articles