0

我有字符串aaabbbccc。获得bbb零件的最佳方法是什么?

升级版:

如何ccc获得aaabbbcccdddfff

4

7 回答 7

2

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

于 2013-08-15T04:13:32.500 回答
1
StringUtils.substringBetween("aaabbbccc", "aaa", "ccc")

StringUtils.substringBetween(...)这里使用

于 2013-08-15T04:14:49.947 回答
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 的返回值

于 2013-08-15T04:17:54.157 回答
0

试试StringUtils.subStringBetween

 String value = "aaabbbccc";
 StringUtils.substringBetween(value, "aaa", "ccc");
于 2013-08-15T04:15:01.323 回答
0

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

String middle = str.replaceAll(".*aaa(.*)ccc.*", "$1");
于 2013-08-15T04:15:38.790 回答
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”存储在结果字符串中。

于 2013-08-15T04:17:40.380 回答
0

最好的方法可能是正则表达式。你可以使用

字符串 str = str.replaceAll(a

于 2013-08-15T05:01:50.987 回答