Java 如何使用子字符串方法打断这4个单词
我想把一个由4个单词组成的句子分成几个单词。但是,我不知道如何告诉它在句子的第一个空格后开始,然后停止,然后是下一个空格Java 如何使用子字符串方法打断这4个单词,java,substring,spaces,Java,Substring,Spaces,我想把一个由4个单词组成的句子分成几个单词。但是,我不知道如何告诉它在句子的第一个空格后开始,然后停止,然后是下一个空格 import java.util.Scanner; public class arithmetic { public static void main(String[] args) { Scanner in = new Scanner(System.in) String sentence; String word1, word2, word3
import java.util.Scanner;
public class arithmetic {
public static void main(String[] args) {
Scanner in = new Scanner(System.in)
String sentence;
String word1, word2, word3, word4;
int p, p2;
System.out.print("Enter a sentence with 4 words:");
sentence = in.nextLine();
p = sentence.indexOf(" ");
word1 = sentence.substring(0,p)+(" ");
word2 = sentence.substring()(" ");
word3 = sentence.substring()+(" ");
word4 = sentence.substring()+(" ");
sentence = word1+word2+word3+word4;
System.out.println(sentence);
这听起来像是你的工作
现在,Word中包含了一个字符串数组,您可以对它们执行任何操作,如将它们转换为另一个句子。您还可以使用
String.split()
方法,如下所示:
import java.util.Scanner;
public class arithmetic {
public static void main(String[] args) {
Scanner in = new Scanner(System.in)
String sentence;
String word1, word2, word3, word4;
int p, p2;
System.out.print("Enter a sentence with 4 words:");
sentence = in.nextLine();
p = sentence.indexOf(" ");
word1 = sentence.substring(0,p)+(" ");
word2 = sentence.substring()(" ");
word3 = sentence.substring()+(" ");
word4 = sentence.substring()+(" ");
sentence = word1+word2+word3+word4;
System.out.println(sentence);
String[] parts = sentence.split("\\s");
这与Chris方法得出的结果完全相同