Tuesday, 10 September 2013

Regex and string arrays in Java

Regex and string arrays in Java

I am attempting to make a simple program which would take in a string
containing 4 words, then split this string into the 4 words, and print all
possible arrangements of these 4 words
Here is the source, the regex is on line 21, which I'm not confident is
correct. Also it really doesn't like my nested for loops
/**
* 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
}
}
}
}
}
}

No comments:

Post a Comment