Java 路径的子字符串,找不到的第二个匹配项\\
我有一根绳子Java 路径的子字符串,找不到的第二个匹配项\\,java,Java,我有一根绳子 "H:\\DVR mo\\Whats app video\\Sent\\VID-20170430-WA0006.mp4" 我想知道字符串中有多少斜杠,我在StringcharAt函数的帮助下找到了它 现在,我知道上面的字符串中有4个斜线。我想选择从索引0到斜杠第二次出现的字符串。因此,预期的结果将是: "H:\\DVR mo" 但是我不知道如何找到第二次出现的索引。如果您想让它处理您明确知道是字符串的字符串,最好的方法可能是按照其他人的建议使用Path类 否则,您将始终使用St
"H:\\DVR mo\\Whats app video\\Sent\\VID-20170430-WA0006.mp4"
我想知道字符串中有多少斜杠,我在StringcharAt函数的帮助下找到了它
现在,我知道上面的字符串中有4个斜线。我想选择从索引0到斜杠第二次出现的字符串。因此,预期的结果将是:
"H:\\DVR mo"
但是我不知道如何找到第二次出现的索引。如果您想让它处理您明确知道是字符串的字符串,最好的方法可能是按照其他人的建议使用Path类 否则,您将始终使用String.split方式。当然,我编写的代码缺少所有检查部分
String s = "H:\\DVR mo\\Whats app video\\Sent\\VID-20170430-WA0006.mp4";
String[] array = s.split("\\");
String result = array[0]+"\\"+array[1];
tl;博士
模块化、独立于平台的解决方案:
String result = StreamSupport.stream(Paths.get(input).spliterator(), false)
.skip(numberOfSubPath - 1)
.findFirst()
.map(Path::toString)
.orElseThrow(IllegalArgumentException::new);
String result = Pattern.compile("\\").splitAsStream(input)
.limit(numberOfSubPath)
.collect(Collectors.joining("\\"));
紧凑但不灵活的解决方案:
String result = StreamSupport.stream(Paths.get(input).spliterator(), false)
.skip(numberOfSubPath - 1)
.findFirst()
.map(Path::toString)
.orElseThrow(IllegalArgumentException::new);
String result = Pattern.compile("\\").splitAsStream(input)
.limit(numberOfSubPath)
.collect(Collectors.joining("\\"));
对于您的示例,请将变量设置为:
String input = "H:\\DVR mo\\Whats app video\\Sent\\VID-20170430-WA0006.mp4";
int numberOfSubPath = 2;
使用路径
如果您的字符串总是表示有效的文件系统路径,则应该考虑将输入解析为路径。因此,请使用Pathsget方法
Path类提供了各种方法来在给定路径上导航,例如getRoot或getParent。由于要创建从第一个文件元素到第二个文件元素的路径,因此将使用Pathiterator: 使用字符串 如果出于某种原因,希望使用字符串执行此任务,我建议使用StringindexOf方法而不是StringcharAt来查找第二个\\事件的索引。然后使用Stringsubstring提取该部分 同样,使用流:您可能应该将URL解析为URL,而不是字符串。例如,作为路径。这样的事情就变得很容易了。做点什么。得到。。。然后使用Path类的方法进行导航。如果确实需要,可以使用input.substringfirstIndex,secondIndex;使用第一步中找到的索引。从java内部创建url时,需要双斜杠。创建路径并提取信息比拆分路径更有意义。同时考虑在你的答案中增加更多的信息,因为它对于新的玩家来说是没有用的。谢谢Zabuz和@ Aniket Sahrawat的评论。尽管如此,Anniket,我不认为他明确要求这个来处理表示路径的字符串,我错了吗?是的…我需要的是将零的子字符串转换成第二个斜杠。。在这种情况下,拆分可能不起作用。…@balsick我可以使用拆分,但在循环中我不能添加数组元素,因为字符串结果=数组[0]+\\+数组[1];
int lastIndex = -1;
for (int i = 0; i < numberOfSubPath; i++) {
// Find the next occurrence starting from 'lastIndex'
lastIndex = input.indexOf("\\", lastIndex);
// There is no next occurrence
if (lastIndex == -1) {
throw new IllegalArgumentException("The input does not have a subpath of number"
+ numberOfSubPath);
}
}
// Extract the text from the beginning to 'lastIndex'
String result = input.substring(0, lastIndex);
// Split the input on each '\\', limit the results
String[] parts = input.split("\\", numberOfSubPath + 1);
// Build the result by concatenating the parts (and adding '\\' again)
StringJoiner result = new StringJoiner("\\");
for (int i = 0; i < numberOfSubPath; i++) {
result.add(parts[i]);
}
System.out.println(result.toString());
String result = Pattern.compile("\\").splitAsStream(input)
.limit(numberOfSubPath)
.collect(Collectors.joining("\\"));