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

标签 java regex string nested-loops

我正在尝试制作一个简单的程序,该程序将接受包含 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/

相关文章:

c - 字符串修改函数 : return void or char*?

java - 线程 "main"java.lang.NoClassDefFoundError : org/apache/http/conn/scheme/SchemeSocketFactory while Using Crawler4j 中出现异常

java - 如何将 sql 查询的结果发布到 servlet 中?

python - 正则表达式初学者 : how to remove comma before a keyword?

java通过正则表达式提取地址项

php - 如何在 preg_replace 中使用数组和正则表达式作为模式?

java - 如何将方法中随机生成的数字附加到数组中

java - 如何将两个int数组混合成唯一的xy坐标Map?

c++ - std::replace 的逻辑错误

java - 如何在字符串中插入≠符号