gpt4 book ai didi

java - Java 中的正则表达式和字符串数组

转载 作者:行者123 更新时间:2023-11-30 04:14:39 24 4
gpt4 key购买 nike

我正在尝试制作一个简单的程序,该程序将接受包含 4 个单词的字符串,然后将该字符串拆分为 4 个单词,并打印这 4 个单词的所有可能排列

这是源代码,正则表达式位于第 21 行,我不确定它是否正确。而且它真的不喜欢我的嵌套 for 循环

 /**


* Author: peaceblaster
* Date 9/10/2013
* Title: hw3
* Purpose: To take in 4 words as a single string, then prints all permutations of the four words
*/

//import stuff
import java.util.Scanner;
public class hw3 {
public static void main(String[] args){
//declarations:
Scanner in = new Scanner(System.in);
String input = new String();
String[] wordArray = new String[4];
int a,b,c,d;
//input
System.out.println("Input 4 words: ");
input = in.next();
//regex
wordArray = input.split("^*[^\s]|\s*\s|*$"); //splits string into array containing each words as a string
// ^* finds first word \s*\s finds words surrounded by spaces *$ finds final word
//output
for (a=1; a=<4; a++){
for (b=1; b=<4; b++){
for (c=1; c=<4; c++){
for (d=1; d=<4; d++){
System.out.println(wordArray[%a] + " " + wordArray[%b] + " " + wordArray[%c] + " " + wordArray[%d]); //uses nested for loops to print permutations as opposed to hard-coding
}
}
}
}
}
}

最佳答案

通过获取输入

String words[] = new String[4];

for (int i = 0; i < words.length; ++i) {
words[i] = in.nextLine();
}

//or
String words[] = in.nextLine().split("\\s+"); //space separated words.

变量名称前不需要使用 %

System.out.println(wordArray[a] + " " + wordArray[b] + " " + wordArray[c] + " " + wordArray[d]);

关于java - Java 中的正则表达式和字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18725094/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com