String s= "aaaaaaaaaaaBBBhelloDDDeeeeBBBworldDDDffffff";
我要挑BBB和DDD之间的内容放到一个字符串数组String[] ss
这是hello和world单词。如何从字符串中选取特定部分?
有没有办法做到这一点?
String s= "aaaaaaaaaaaBBBhelloDDDeeeeBBBworldDDDffffff";
我要挑BBB和DDD之间的内容放到一个字符串数组String[] ss
这是hello和world单词。如何从字符串中选取特定部分?
有没有办法做到这一点?
使用函数substring(int beginIndex,int endIndex)。 如果您可以对索引进行硬编码。
使用String.split("BBB")
和String.split("DDD")
例如为:
String[] splitByBBB = s.split("BBB");
/*
in your String:
splitByBBB[0] is "aaaaaaaaaaa"
splitByBBB[1] is "helloDDDeeee"
splitByBBB[2] is "worldDDDffffff"
*/
然后使用split("DDD")
和采取的第一个指标:
String[] ss = new String[ splitByBBB.length - 1 ];
for(int i = 0; i < splitByBBB.length; i++)
{
ss[i] = splitByBBB[i + 1].split("DDD")[0];
}
/*
in your String:
ss[0] is "hello"
ss[1] is "world"
*/
String[] array = s.split("BBB|DDD");
您可以使用模式匹配:
String s= "aaaaaaaaaaaBBBhelloDDDeeeeBBBworldDDDffffff";
Pattern p = Pattern.compile("BBB(.+?)DDD",Pattern.DOTALL);
Matcher m = p.matcher(s);
ArrayList<String> sa = new ArrayList<String>();
while (m.find()) {
sa.add(m.group(1));
}
System.out.println(sa);
是的,有。正则表达式会以相当简单的方式进行。但在此之前,我们可以看看你做了什么以及你面临的问题吗? – SudoRahul
你有什么尝试?这似乎是正则表达式最直接的用法 – Ordous