When I perform
String test=\"23x34 \";
String[] array=test.split(\"x\"); //splitting using simple letter
I got two items in array as 23 and
split
uses, as the documentation suggests, a regexp. a regexp for your example would be :
"[xX]"
Also, the (?i)
flag toggles case insensitivty. Therefore, the following is also correct :
"(?i)x"
In this case, x
can be any litteral properly escaped.
I personally prefer using
String modified = Pattern.compile("x", Pattern.CASE_INSENSITIVE).matcher(stringContents).replaceAll(splitterValue);
String[] parts = modified.split(splitterValue);
In this way you can ensure any regex will work, as long as you have a unique splitter value
Java's String class' split method also accepts regex.
To keep things short, this should help you: http://www.coderanch.com/t/480781/java/java/String-split
You can also use an embedded flag in your regex:
String[] array = test.split("(?i)x"); // splits case insensitive
You could use a regex as an argument to split
, like this:
"32x23".split("[xX]");
Or you could use a StringTokenizer
that lets you set its set of delimiters, like this:
StringTokenizer st = new StringTokenizer("32x23","xX");
// ^^ ^^
// string delimiter
This has the advantage that if you want to build the list of delimiters programatically, for example for each lowercase letter in the delimiter list add its uppercase corespondent, you can do this and then pass the result to the StringTokenizer
.
Use regex pattern [xX]
in split
String x = "24X45";
String[] res = x.split("[xX]");
System.out.println(Arrays.toString(res));