如何将字符串子串到java中的最后一个点(.)?

new*_*mer 3 java split

我有一个文本文件data.txt.我想将数据输入到Hashmap中并进行一些数据映射.什么时候我没有点()来达到值.我会收到一个错误

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
Run Code Online (Sandbox Code Playgroud)

如何通过跳过没有点(.)的条目来克服它.

我创建了一个小片段来说明我的问题.

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

    }
Run Code Online (Sandbox Code Playgroud)

data.txt中

0
0.1
0.2
0.3.5.6
0.2.1
2.2
Run Code Online (Sandbox Code Playgroud)

打印地图时的预期结果(不需要按顺序)

0
0
0.3.5
0.2
2
Run Code Online (Sandbox Code Playgroud)

Deb*_*Ray 6

使用String方法lastIndexOf(int ch).

int lastIndxDot = st.lastIndexOf('.');
Run Code Online (Sandbox Code Playgroud)

st.substring(0, lastIndxDot);将是你想要的子串.如果它返回-1,那么就没有'.' 在字符串中.

编辑:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)