Arkan
Arkan

Reputation: 65

Select a word on a phrase from string of Array Java

Input phrase : take a word out of the phrase and print it

Output : the

I've tried using split, but it seems like that wasn't how it work

But here is my code

public class Main  
{   
    public static void main(String args[])   
    {   
        
        String str              = "take a word out of the phrase and print it";  
        String[] stringarray    = str.split("take a word out of the phrase ",0);   
        String[] stringarray1   = str.split(" of the phrase and print it",0);
        String[] stringarray2   = str.split("of the",0);
        String[] stringarray3   = str.split("the",0);

        // This one doesn't work the way I wanted
        String[] stringarray4   = str.split("take a word out of  phrase and print it",0);
        
        for(int i=0; i<stringarray.length; i++)  
        {  
            System.out.println(stringarray[i]);  
        }
        for(int i=0; i<stringarray1.length; i++)  
        {  
            System.out.println(stringarray1[i]);  
        }
        for(int i=0; i<stringarray2.length; i++)  
        {  
            System.out.println(stringarray2[i]);  
        }
        for(int i=0; i<stringarray3.length; i++)  
        {  
            System.out.println(stringarray3[i]);  
        }
        for(int i=0; i<stringarray4.length; i++)  
        {  
            System.out.println(stringarray4[i]);  
        }
        
    }   
}  

Below is the output of the program above

[1]and print it
[2]take a word out
[3]take a word out 
   phrase and print it
[4]take a word out of 
   phrase and print it
[5]take a word out of the phrase and print it
// I want "the" on the fifth output to be gone

Upvotes: 1

Views: 307

Answers (2)

sanjeevRm
sanjeevRm

Reputation: 1606

You can split string by space into two part and print only second part like this

        String str   = "take a word out of the phrase and print it";  
        int numberOfWords = str.split(" ").length;
        String reducedPhrase = str;
         
        for(int i=0; i<numberOfWords-1; i++) {
            reducedPhrase = reducedPhrase.split(" ", 2)[1];
            System.out.println("reducedPhrase:"+ reducedPhrase);
        }

Upvotes: 1

Roberto Messa
Roberto Messa

Reputation: 71

build a new string after remove the word

  1. find the string index
  2. copy from index to index + length

String input = "take a word out of the phrase and print it";
String target = "the";

int start = input.indexOf(target);
int finish = start + target.length;
String output = input.substring(start, finish);

Upvotes: 1

Related Questions