- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我有一个文本文件 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/
我正在尝试创建一个程序,其中字符串的前三个字符重复给定次数,如下所示: foo('Chocolate', 3) # => 'ChoChoCho' foo('Abc', 3) # => 'AbcAbcA
我有以下字符串: std::string str = "Mode:AAA:val:101:id:A1"; 我想分离一个位于 "val:" 和 ":id" 之间的子字符串,这是我的方法: std::st
DNA 字符串可以是任意长度,包含 5 个字母(A、T、G、C、N)的任意组合。 压缩包含 5 个字母(A、T、G、C、N)的 DNA 字母串的有效方法是什么?不是考虑每个字母表 3 位,我们可以使用
是否有一种使用 levenstein 距离将一个特定字符串与第二个较长字符串中的任何区域进行匹配的好方法? 例子: str1='aaaaa' str2='bbbbbbaabaabbbb' if str
使用 OAuth 并使用以下函数使用我们称为“foo”(实际上是 OAuth token )的字符串加密 key public function encrypt( $text ) { // a
我是一名优秀的程序员,十分优秀!