Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

split

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
like image 950
newbieprogrammer Avatar asked Feb 08 '23 10:02

newbieprogrammer


1 Answers

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);
    }
}
like image 67
Debosmit Ray Avatar answered Feb 12 '23 14:02

Debosmit Ray