i have a string in Java.
1|2|3|4|5|2|2|3|4|123441|234556|67783|56764|55454
i want to count a delimiter above string . Please help me in how to count and i want only starting 7 Delimiter value.
You can split using |
character.
public static void main(String[] args) {
String s = "1|2|3|4|5|2|2|3|4|123441|234556|67783|56764|55454";
String[] strArr = s.split("\\|");
System.out.println("Array : " + Arrays.toString(strArr));
System.out.println("Delimiter count : " + (strArr.length - 1)); // Prints 13
System.out.println("7th field : " + strArr[7]); // Prints 3
}
You can solve it with regular expressions, using Pattern and Matcher classes:
String s = "1|2|3|4|5|2|2|3|4|123441|234556|67783|56764|55454";
Pattern p = Pattern.compile("((\\d+\\|){7}).*");
Matcher m = p.matcher(s);
if (m.matches()) {
System.out.println(m.group(1));
}
To understand the code above, have a look at regular expressions, eg http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
In case if your input string if sthg like this:-
1|2|3|4|5|2|2|3|4|123441|234556|||
having empty values between delimiters. Then you can go with a different version of split
function.
String[] strArr = s.split("\\|", -1);
You need to pass -1 as the second argument to split otherwise it removes empty strings.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.