One way we can use this is to use a backslash \ . For example: string. split("\\|");
use \\| instead of | to escape it.
Use method String. split() It returns an array of String, splitted by the character you specified.
Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.
|
is a metacharacter in regex. You'd need to escape it:
String[] value_split = rat_values.split("\\|");
String[] value_split = rat_values.split(Pattern.quote("|"));
//System.out.println(Arrays.toString(rat_values.split(Pattern.quote("|")))); //(FOR GETTING OUTPUT)
String[] value_split = rat_values.split("\\|");
//System.out.println(Arrays.toString(rat_values.split("\\|"))); //(FOR GETTING OUTPUT)
public static String[] splitUsingTokenizer(String Subject, String Delimiters)
{
StringTokenizer StrTkn = new StringTokenizer(Subject, Delimiters);
ArrayList<String> ArrLis = new ArrayList<String>(Subject.length());
while(StrTkn.hasMoreTokens())
{
ArrLis.add(StrTkn.nextToken());
}
return ArrLis.toArray(new String[0]);
}
Arrays.asList(Pattern.compile("\\|").split(rat_values))
//System.out.println(Arrays.asList(Pattern.compile("\\|").split(rat_values))); //(FOR GETTING OUTPUT)
[Food 1 , Service 3 , Atmosphere 3 , Value for money 1 ]
Or.. Pattern#quote
:
String[] value_split = rat_values.split(Pattern.quote("|"));
This is happening because String#split
accepts a regex:
|
has a special meaning in regex.
quote
will return a String representation for the regex.
split takes regex as a parameter.|
has special meaning in regex.. use \\|
instead of |
to escape it.
String rat_values = "Food 1 | Service 3 | Atmosphere 3 | Value for money 1 ";
String[] value_split = rat_values.split("\\|");
for (String string : value_split) {
System.out.println(string);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With