fast way to get an element from a string in java

2019-09-13 03:16发布

问题:

I am trying to get an element from my string wich I have attained thtough a getSelectedValue().toString from a JList. It returns [1] testString

What I am trying to do it only get the 1 from the string. Is there a way to only get that element from the string or remove all else from the string?

I have tried:

String longstring = Customer_list.getSelectedValue().toString();
int index = shortstring.indexOf(']');
String firstPart = myStr.substring(0, index); 

回答1:

You have many ways to do it, for example

  1. Regex
  2. String#replaceAll
  3. String#substring

See below code to use all methods.

import java.util.*;
import java.lang.*;
import java.util.regex.Matcher;  
import java.util.regex.Pattern;

class Test {  
    public static void main(String args[]) {
    String[] data = { "[1] test", " [2] [3] text ", " just some text " };

    for (String s : data) {
        String r0 = null;
        Matcher matcher = Pattern.compile("\\[(.*?)\\]").matcher(s);
        if (matcher.find()) {
            r0 = matcher.group(1);
        }
        System.out.print(r0 + " ");
    }
    System.out.println();

    for (String s : data) {
        String r1 = null;
        r1 = s.replaceAll(".*\\[|\\].*", "");
        System.out.print(r1 + " ");
    }
    System.out.println();

    for (String s : data) {
        String r2 = null;
        int i = s.indexOf("[");
        int j = s.indexOf("]");
        if (i != -1 && j != -1) {
            r2 = s.substring(i + 1, j);
        }
        System.out.print(r2 + " ");
    }
    System.out.println();
    }
}

However results may vary, for example String#replaceAll will give you wrong results when input is not what you expecting.

1 2 null

1 3 just some text

1 2 null



回答2:

What worked best for me is the String#replace(charSequence, charSequence) combined with String#substring(int,int)

I have done as followed:

        String longstring = Customer_list.getSelectedValue().toString();
        String shortstring = longstring.substring(0, longstring.indexOf("]") + 1);
        String shota = shortstring.replace("[", "");
        String shortb = shota.replace("]", "");

My string has been shortened, and the [ and ] have been removed thereafter in 2 steps.