且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何用Java解析这个字符串?

更新时间:2023-02-12 18:22:00

如果你想拆分字符串 / 字符处, 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.