Get string value before special character in java
This seems like a simple problem, but I can't figure it out.
I have the following array of strings getting the result:
21|Commercial Property Green
100|Social Services Commercial Property
5|Social Services Professional
6501|Personal Property
I only need a part of the line number (i.e. 21, 100, 5 and 6501 and they can be strings without requiring them to be integers). How should I do it?
Let me know if you need more information.
source to share
You could do something simple, assuming that you have inserted each element in the array
public class StringSplit {
public static void main(String[] args) {
String[] lines = new String[]{"21|Commercial Property Green Endorsement",
"100|Social Services Commercial Property Endorsement",
"5|Social Services Professional Liability",
"6501|Personal Property Liability"};
for (String string : lines) {
String num = string.split("\\|")[0];
System.out.println(num);
}
}
}
source to share
Why not another answer using a cool new Java 8 feature :)
String[] stringArray = new String[] {
"21|Commercial Property Green Endorsement",
"100|Social Services Commercial Property Endorsement",
"5|Social Services Professional Liability",
"6501|Personal Property Liability"
};
int[] intArray = Arrays.stream(stringArray).mapToInt(s -> Integer.parseInt(s.split("\\|")[0])).toArray();
source to share
for (int i=0; i< results.length(); i++) {
results[i].split("\\|")[0];}
Split () is a method defined in the String class
public String[] split(String regex) {
return split(regex, 0);
}
Escape characters (also called escape sequences or escape codes) are typically used to signal an alternative interpretation of a number of characters. In Java, a character preceded by a backslash () is an escape sequence and has special meaning to the java compiler. We use \ as escape character, otherwise '|' will not be considered.
It splits and returns a String array, as you can see in the definition of Split ().
source to share