1

I am trying to allow the user to remove a word from the string str. For example if they type "Hello my name is john", The output should be "Hello is john". How do i make this happen?

import java.util.*;
class WS7Q2{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);

        System.out.println("Please enter a sentence");
        String str = in.nextLine();

        int j;

        String[] words = str.split(" "); 
        String firstTwo = words[0] + "  " + words[1]; // first two words
        String lastTwo = words[words.length - 2] + " " + words[words.length - 1];//last two   words 

        System.out.println(str);

    }
}
Paul Samsotha
  • 197,959
  • 33
  • 457
  • 689

3 Answers3

2

This is how you split the string

String myString = "Hello my name is John";

String str = myString.replace("my name", "");
System.out.println(str);

This will print "Hello is John"

I am Cavic
  • 1,105
  • 1
  • 10
  • 22
1

Why not just use String#replace()

String hello = "Hello my name is john"

hello = hello.replace("my name", "");

System.out.println(hello);
Paul Samsotha
  • 197,959
  • 33
  • 457
  • 689
0

String is immutable in java, you cannot modify the string itself (not easily anyway, can be done using reflection - but it is unadvised).

You can bind a new string to str with minimal changes to your code using something similar to:

str = firstTwo + " " + lastTwo;
Community
  • 1
  • 1
amit
  • 172,148
  • 26
  • 225
  • 324