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.

+3


source to share


7 replies


If all the lines of the array are in the same format, you can use the following



 for(int i=0;i<arr.length();i++){
  System.out.println(arr[i].substring(0,arr[i].indexOf('|')));
}

      

+2


source


You guys love regex too much ....



int x = line.indexOf('|');
if(x==-1) 
    ... parse error
else
    return line.substring(0,x);

      

+3


source


You can also use the method split()

String str = "21|Commercial Property Green Endorsement";
String[] parts = str.split("\\|");
String part1 = parts[0]; // 21
String part2 = parts[1]; // Commercial Property Green Endorsement

      

+1


source


Use a regular expression ([^|]+)

.

Pattern pattern = Pattern.compile("([^|]+)");
Matcher matcher = pattern.matcher(str);
if(matcher.find()) {
    int number = Integer.parseInt(matcher.group(1));
    ...
}

      

0


source


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);
    }
  }

}

      

0


source


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();

      

0


source


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 ().

0


source







All Articles