如何获取某些东西之间的字符串?

时间:2013-08-15 04:11:08

标签: java string

我有字符串aaabbbccc。获取bbb部分的最佳方式是什么?

UPD:

如何从ccc获取aaabbbcccdddfff

7 个答案:

答案 0 :(得分:2)

s.substring(s.indexOf("b"), s.lastIndexOf("b")-1)

答案 1 :(得分:1)

StringUtils.substringBetween("aaabbbccc", "aaa", "ccc")

使用here

中的StringUtils.substringBetween(...)

答案 2 :(得分:1)

在这种特定情况下,

String bbbString = "aaabbbccc".substring(3,6);

为了回答您刚刚添加到问题中的位,我想说使用以下功能

public String getRepetitiveSubstringOf(String string, char desiredCharacter)
{
String theSubstring = null;
char[] charArray = string.toCharArray();   //it is more efficient to use arrays
//get the beginning position
int beginPosition = string.indexOf(desiredCharacter);
//get the end position (the desired substring length might NOT be 3, but rather, in this case, 
//where the character value changes)
int endPosition = beginPosition;
//looping until we have either found a different character, or until we have hit the end of the 
//character array (at the end, we loop one more time so that we can hit a garbage value that 
//tells us to stop)
while ((charArray[endPosition] == desiredCharacter) || (endPosition < charArray.length))
{
    endPosition++;
}
//if we have hit the garbage value
if (endPosition == charArray.length)
{
    //we substring all the way to the end
    theSubstring = string.substring(beginPosition);
}
else
{
    //now, we check to see if our desiredCharacter was found AT ALL in the string
    if (desiredCharacter > -1)
    {
        theSubstring = string.substring(beginPosition, endPosition);
    }
}
return theSubstring;
}

从那里,您可以检查返回值为null

答案 3 :(得分:0)

尝试StringUtils.subStringBetween

 String value = "aaabbbccc";
 StringUtils.substringBetween(value, "aaa", "ccc");

答案 4 :(得分:0)

如果使用正则表达式捕获目标组,则只需要一行和一个方法调用:

String middle = str.replaceAll(".*aaa(.*)ccc.*", "$1");

答案 5 :(得分:0)

对于您指定的字符串,您可以使用以下代码:

String result=s.substring(s.indexOf('b'),s.lastIndexOf('b'));

其中s是你的字符串,

更一般的字符串:

String result =s.substring(first index,last index);

其中第一个索引和最后一个索引是您要提取的范围。 例如:

String S="rosemary";
String result=s.substring(4,s.length());

这会在结果字符串中存储“mary”。

答案 6 :(得分:0)

最好的方式可能是regEx.You可以使用

String str = str.replaceAll(a