gpt4 book ai didi

java - 如何在 java 中将字符串子串到最后一个点 (.) 之前?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:41:45 25 4
gpt4 key购买 nike

我有一个文本文件 data.txt。我想将数据输入 Hashmap 并进行一些数据映射。每当我在没有点()的情况下达到该值时。我会得到一个错误

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

如何通过跳过那些不带点 (.) 的条目来克服它。

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

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

}

数据.txt

0
0.1
0.2
0.3.5.6
0.2.1
2.2

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

0
0
0.3.5
0.2
2

最佳答案

使用字符串方法lastIndexOf(int ch)

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

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

关于java - 如何在 java 中将字符串子串到最后一个点 (.) 之前?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36193729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com