如何用Java解析这个字符串? [英] How to parse this string in Java?

查看:128
本文介绍了如何用Java解析这个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


前缀/ dir1 / dir2 / dir3 / dir4 /..

prefix/dir1/dir2/dir3/dir4/..

如何解析 dir1,dir2 Java中上述字符串的值是什么?

How to parse the dir1, dir2 values out of the above string in Java?

这里的前缀可以是:

/ usr / local / apache2 / resumes

/usr/local/apache2/resumes

推荐答案

如果你想拆分字符串 / 字符处, String.split 方法将工作:

If you want to split the String at the / character, the String.split method will work:

例如:

String s = "prefix/dir1/dir2/dir3/dir4";
String[] tokens = s.split("/");

for (String t : tokens)
  System.out.println(t);

输出

prefix
dir1
dir2
dir3
dir4

编辑

前缀为 / 的情况,我们知道前缀是什么:

Case with a / in the prefix, and we know what the prefix is:

String s = "slash/prefix/dir1/dir2/dir3/dir4";

String prefix = "slash/prefix/";
String noPrefixStr = s.substring(s.indexOf(prefix) + prefix.length());

String[] tokens = noPrefixStr.split("/");

for (String t : tokens)
  System.out.println(t);

没有前缀的子字符串slash / prefix / substring 方法。那么 String 然后通过 split 运行。

The substring without the prefix "slash/prefix/" is made by the substring method. That String is then run through split.

输出:

dir1
dir2
dir3
dir4

再次修改

如果 String 实际上是使用 文件 类可能比使用字符串操作更可取。像 File 这样的类已经考虑到了处理文件路径的所有复杂性,这些类会更加健壮。

If this String is actually dealing with file paths, using the File class is probably more preferable than using string manipulations. Classes like File which already take into account all the intricacies of dealing with file paths is going to be more robust.

这篇关于如何用Java解析这个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆