Reputation: 63
My characters is "!
,;
,%
,@
,**
,**
,(
,)
" which get from XML. when I split it with ',
', I lost the ',
'.
How can I do to avoid it. I have already tried to change the comma to 'C', but it does not work.
Thre result I want is "!
,;
,%
,@
,,
,(
,)
", but not "!
,;
,%
,@
,,
(
,)
"
Upvotes: 0
Views: 89
Reputation: 23047
First, we need to define when the comma is an actual delimiter, and when it is part of a character sequence.
We need to assume that a sequence of commas surrounded by commas is an actual character sequence we want to capture. It can be done with lookarounds:
String s = "!,;,,,%,@,**,**,,,,(,)";
List<String> list = Arrays.asList(s.split(",(?!,)|(?<!,),"));
This regular expression splits by a comma that is either preceded by something that is not a comma, or followed by something that is not a comma.
Note that your formatting string, that is, every character sequence separated by a comma, is a bad design, since you require both the possibility to use a comma as sequence, and the possibility to use multiple characters to be used. That means you can combine them too!
What, for example, if I want to use these two character sequences:
,
,,,,
Then I construct the formatting string like this: ,,,,,,
. It is now unclear whether ,
and ,,,,
should be character sequences, or ,,
and ,,,
.
Upvotes: 0
Reputation: 60046
String::split use regex so you can split with this regex ((?<!,),|,(?!,))
like this :
String string = "!,;,%,@,,,(,)";
String[] split = string.split("((?<!,),|,(?!,))");
Details
(?<!,),
match a comma if not preceded by a comma|
or,(?!,)
match a comma if not followed by a commaOutputs
!
;
%
@
,
(
)
Upvotes: 2
Reputation: 1042
try this, this could be help full. First I replaced the ',' with other string and do split. After complete other string replace with ','
public static void main(String[] args) {
String str = "!,;,%,@,**,**,(,)";
System.out.println(str);
str = str.replace("**,**","**/!/**");
String[] array = str.split(",");
System.out.println(Arrays.stream(array).map(s -> s.replace("**/!/**", ",")).collect(Collectors.toList()));
}
out put
!,;,%,@,**,**,(,)
[!, ;, %, @, ,, (, )]
Upvotes: 0
Reputation: 154
If you are trying to extract all characters from string, you can do so by using String.toCharArray()
[1] :
String str = "sample string here";
char[] char_array = s.toCharArray();
If you just want to iterate over the characters in the string, you can use the character array obtained from above method or do so by using a for loop and str.charAt(i)
[2] to access the character at position i.
[1] https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toCharArray() [2]https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#charAt(int)
Upvotes: 0