从字符串中提取子字符串

Moe*_*Moe 66 string android substring

从android中的字符串中提取子字符串的最佳方法是什么?

Kar*_*iya 126

如果您知道开始和结束索引,则可以使用

String substr=mysourcestring.substring(startIndex,endIndex);
Run Code Online (Sandbox Code Playgroud)

如果您想从特定索引到结束获取子字符串,您可以使用:

String substr=mysourcestring.substring(startIndex);
Run Code Online (Sandbox Code Playgroud)

如果你想从特定字符到结束获取子字符串,你可以使用:

String substr=mysourcestring.substring(mysourcestring.indexOf("characterValue"));
Run Code Online (Sandbox Code Playgroud)

如果要从特定字符获取子字符串,请将该数字添加到.indexOf(char):

String substr=mysourcestring.substring(mysourcestring.indexOf("characterValue") + 1);
Run Code Online (Sandbox Code Playgroud)


Mit*_*eat 78

substring():

str.substring(startIndex, endIndex); 
Run Code Online (Sandbox Code Playgroud)

  • 简单而完美 (2认同)

gpw*_*pwr 26

这是一个真实世界的例子:

String hallostring = "hallo";
String asubstring = hallostring.substring(0, 1); 
Run Code Online (Sandbox Code Playgroud)

在示例中,asubstring将返回:h

  • 该答案隐式地添加了其他两个更流行的答案所缺少的信息,即字符串是0,而不是基于1的字符串,并且应该获得比这样做更多的爱。 (3认同)
  • 重要的不是基础。子字符串采用从startIndex位置开始一直延伸到但不包括endIndex的部分字符串。 (2认同)
  • 基础不重要???知道索引从零运行到 string.length() ,并且返回的最后一个字符是由 endIndex-1 索引的字符,这是令人难以置信的重要,你不是说吗? (2认同)

小智 14

如果你想在一个字符之前和之后获得子字符串,还有另一种方法

String s ="123dance456";
String[] split = s.split("dance");
String firstSubString = split[0];
String secondSubString = split[1];
Run Code Online (Sandbox Code Playgroud)

检查此帖子 - 如何在字符串中的子字符串之前和之后查找


sHO*_*OLE 9

substring(int startIndex, int endIndex)

如果不指定endIndex,则该方法将返回startIndex中的所有字符。

startIndex:起始索引包括在内

endIndex:结束索引是排他的

例:

String str = "abcdefgh"

str.substring(0, 4) => abcd

str.substring(4, 6) => EF

str.substring(6) => gh


Joh*_*ith 5

你可以使用这个代码

    public static String getSubString(String mainString, String lastString, String startString) {
    String endString = "";
    int endIndex = mainString.indexOf(lastString);
    int startIndex = mainString.indexOf(startString);
    Log.d("message", "" + mainString.substring(startIndex, endIndex));
    endString = mainString.substring(startIndex, endIndex);
    return endString;
}
Run Code Online (Sandbox Code Playgroud)

mainString是一个超级字符串,例如“I_AmANDROID.Devloper”,并且lastString是一个类似“.”的字符串。startString 就像“_”。所以这function会返回“AmANDROID”。享受你的编码时间。:)