Java 字符串中的单词如何删除
我试图允许用户从字符串str中删除一个单词。 例如,如果他们键入“Hello my name is john”,则输出应为“Hello is john”。 我该如何做到这一点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
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);