Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 字符串中的单词如何删除_Java_String - Fatal编程技术网

Java 字符串中的单词如何删除

Java 字符串中的单词如何删除,java,string,Java,String,我试图允许用户从字符串str中删除一个单词。 例如,如果他们键入“Hello my name is john”,则输出应为“Hello is john”。 我该如何做到这一点 import java.util.*; class WS7Q2{ public static void main(String[] args){ Scanner in = new Scanner(System.in); System.out.println("Please ente

我试图允许用户从字符串str中删除一个单词。 例如,如果他们键入“Hello my name is john”,则输出应为“Hello is john”。 我该如何做到这一点

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);

    }
}

String
在java中是不可变的,您不能修改字符串本身(无论如何都不容易)

您可以使用以下类似的方法将新字符串绑定到
str
,只需对代码进行少量更改:

str = firstTwo + " " + lastTwo;

这就是分割字符串的方式

String myString = "Hello my name is John";

String str = myString.replace("my name", "");
System.out.println(str);
这将打印“Hello is John”

为什么不直接使用

str=str.replace(“我的名字”和“”)
String hello = "Hello my name is john"

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

System.out.println(hello);