javastringtextwords

Copy the first N words in a string in java


I want to select the first N words of a text string. I have tried split() and substring() to no avail. What I want is to select the first 3 words of the following prayer and copy them to another variable.

For example if I have a string:

String greeting = "Hello this is just an example"

I want to get into the variable Z the first 3 words so that

Z = "Hello this is"

Solution

  •     String myString = "Copying first N numbers of words to a string";
        String [] arr = myString.split("\\s+"); 
             //Splits words & assign to the arr[]  ex : arr[0] -> Copying ,arr[1] -> first
    
    
            int N=3; // NUMBER OF WORDS THAT YOU NEED
            String nWords="";
    
            // concatenating number of words that you required
            for(int i=0; i<N ; i++){
                 nWords = nWords + " " + arr[i] ;         
            }
    
        System.out.println(nWords);
    



    NOTE : Here .split() function returns an array of strings computed by splitting a given string around matches of the given regular expression

    so if i write the code like follows

    String myString = "1234M567M98723651";
    String[] arr = myString.split("M"); //idea : split the words if 'M' presents
    

    then answers will be :
    1234 and 567 where stored into an array.

    This is doing by storing the split values into the given array. first split value store to arr[0], second goes to arr[1].

    Later part of the code is for concatenating the required number of split words

    Hope that you can get an idea from this!!!
    Thank you!