Java – split string – Cartesian
•
Java
The following string is given:
“foo bar-baz-zzz”
I want to divide it into the characters "" and "-", keep their values, but get all the input combinations
I want to get a two-dimensional array
{{"foo","bar","baz","zzz"},{"foo bar",{"foo","bar-baz",{"foo bar-baz","baz-zzz"},"bar-baz-zzz"},{"foo bar-baz-zzz"}}
Is there any built-in method in Java to split strings in this way? Maybe in a library like Apache Commons? Or do I have to write a for loop wall?
Solution
This is an effective recursive solution I used list < list < string > > instead of a two-dimensional array to make things easier The code is a little ugly. It may be sorted out
Sample output:
$java Main foo bar-baz-zzz Processing: foo bar-baz-zzz [foo,bar,baz,zzz] [foo,baz-zzz] [foo,bar-baz,bar-baz-zzz] [foo bar,zzz] [foo bar,baz-zzz] [foo bar-baz,zzz] [foo bar-baz-zzz]
Code:
import java.util.*; public class Main { public static void main(String[] args) { // First build a single string from the command line args. StringBuilder sb = new StringBuilder(); Iterator<String> it = Arrays.asList(args).iterator(); while (it.hasNext()) { sb.append(it.next()); if (it.hasNext()) { sb.append(' '); } } process(sb.toString()); } protected static void process(String str) { System.err.println("Processing: " + str); List<List<String>> results = new LinkedList<List<String>>(); // Invoke the recursive method that does the magic. process(str,results,new LinkedList<String>(),new StringBuilder()); for (List<String> result : results) { System.err.println(result); } } protected static void process(String str,int pos,List<List<String>> resultsSoFar,List<String> currentResult,StringBuilder sb) { if (pos == str.length()) { // Base case: Reached end of string so add buffer contents to current result // and add current result to resultsSoFar. currentResult.add(sb.toString()); resultsSoFar.add(currentResult); } else { // Step case: Inspect character at pos and then make recursive call. char c = str.charAt(pos); if (c == ' ' || c == '-') { // When we encounter a ' ' or '-' we recurse twice; once where we treat // the character as a delimiter and once where we treat it as a 'normal' // character. List<String> copy = new LinkedList<String>(currentResult); copy.add(sb.toString()); process(str,pos + 1,resultsSoFar,copy,new StringBuilder()); sb.append(c); process(str,currentResult,sb); } else { sb.append(c); process(str,sb); } } } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码