简体   繁体   中英

How to substring a string to the before last dot(.) in java?

I have a text file data.txt. I want to input the data into a Hashmap and do some datamapping. When ever I hit the value without dot(). I will get an error

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1

How to I overcome it by skipping those entry without dot(.).

I created a small snippet to illustrate my problem.

  static HashMap<String, String> newList = new HashMap<>();
    public static void main(String[] args) throws FileNotFoundException, IOException {
        String inputFile = "data.txt";
        BufferedReader brInput = new BufferedReader(new FileReader(inputFile));
        String line;

        while ((line = brInput.readLine()) != null) {
            newList.put(line, "x");
        }

        for (Map.Entry<String, String> entry : newList.entrySet()) {

            String getAfterDot = entry.getKey();
            String[] split = getAfterDot.split("\\.");
            String beforeDot = "";
            beforeDot = getAfterDot.substring(0, getAfterDot.lastIndexOf("."));
            System.out.println(beforeDot);
        }

    }

data.txt

0
0.1
0.2
0.3.5.6
0.2.1
2.2

expected result when i print the map(doesnt need to be in order)

0
0
0.3.5
0.2
2

Use the String method lastIndexOf(int ch) .

int lastIndxDot = st.lastIndexOf('.');

st.substring(0, lastIndxDot); will be the substring you want. If it returned -1, then there is no '.' in the string.

EDIT:

for (Map.Entry < String, String > entry: newList.entrySet()) {
    String getAfterDot = entry.getKey();
    int lastIndxDot = getAfterDot.lastIndexOf('.');
    if (lastIndxDot != -1) {
        String beforeDot = getAfterDot.substring(0, lastIndxDot);
        System.out.println(beforeDot);
    }
}

Try this code it should work:

static HashMap < String, String > newList = new HashMap < > (); 
public static void main(String[] args) throws FileNotFoundException, IOException {

    String inputFile = "input";
    BufferedReader brInput = new BufferedReader(new FileReader(inputFile));
    String line = null;

    while ((line = brInput.readLine()) != null) {

        newList.put(line, "x");
    }

    for (Map.Entry < String, String > entry: newList.entrySet()) {

        String getAfterDot = entry.getKey();
        if (getAfterDot.contains(".")) {
            String[] split = getAfterDot.split("\\.");
            String beforeDot = "";
            beforeDot = getAfterDot.substring(0, getAfterDot.lastIndexOf("."));
            System.out.println(beforeDot);
        }
    }

}

I got this output with above code:

0
0
2
0.3.5
0.2

You may check to see if the string has a dot before by using getAfterDot.contains(".") before invoking the substring function on the string.

static HashMap<String, String> newList = new HashMap<String, String>();
public static void main(String[] args) throws FileNotFoundException, IOException {
    String inputFile = "data.txt";
    BufferedReader brInput = new BufferedReader(new FileReader(inputFile));
    String line;
    while ((line = brInput.readLine()) != null) {
        newList.put(line, "x");
    }
    for (Map.Entry<String, String> entry : newList.entrySet()) {
        String getAfterDot = entry.getKey();
        String[] split = getAfterDot.split("\\.");
        String beforeDot = "";
        if(getAfterDot.contains(".")){
            beforeDot = getAfterDot.substring(0, getAfterDot.lastIndexOf("."));
            System.out.println(beforeDot);
        }
    }

}

One option would be to use String.replaceAll() with a regex which extracts out the portion of the string coming before the period (if the period exists).

for (Map.Entry<String, String> entry : newList.entrySet()) {
    String getAfterDot = entry.getKey();
    String beforeDot = getAfterDot.replaceAll("(.*)\\..*", "$1");
    System.out.println(beforeDot);
}
    String[] lines = new String[]{"0", "0.1", "0.2", "0.3.5.6", "0.2.1", "2.2"};
    for (String line : lines) {
        int lastIndexOf = line.lastIndexOf(".");
        if (lastIndexOf > -1) {
            line = line.substring(0, lastIndexOf);
            System.out.println(line);
        }
    }

If you are fine with using libraries, you don't need to re-invent the wheel:

beforeDot = StringUtils.substringBeforeLast(getAfterDot, ":");

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#substringBeforeLast-java.lang.String-java.lang.String-

我只是想我会指出这可以在一行代码中完成:

foo.substringAfterLast(".")

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM