简体   繁体   English

如何获取字符串中第一个和最后一个字符的索引?

[英]How can i get the index of the first and last char in string?

Assume the below string : 假设以下字符串:

String value = "161207CAD140000,0";

how can i get the index of the first char and the index of the last char for the substring CAD notice that the size of the substring may be changed from 2 ,3 or etc chars i want the solution to be dynamic. 我如何获得子字符串CAD的第一个字符的索引和最后一个字符的索引,请注意,子字符串的大小可以从2,3或其他字符更改,我希望解决方案是动态的。

You can use String.indexOf(String str) function which will return starting indexof the "CAD". 您可以使用String.indexOf(String str)函数,该函数将返回“ CAD”的起始索引。 Then add one less then the length of String to find in the returned value, that will be your last character index of "CAD". 然后再加上一个比字符串长度少的值,以找到返回的值,该值将是您的最后一个字符索引“ CAD”。

Something like this: 像这样:

String value = "161207CAD140000,0";
String str = "CAD";
String datePart = value.substring(0, value.indexOf(str)); // for finding the date part
String amountStr = value.substring(value.indexOf(str) + str.length()); //for finding the amount part
System.out.println(datePart +"  "+amountStr);`

Now suppose the String "CAD" is dynamic and you don't know what value it will have, in that case its better to use regex. 现在假设字符串“ CAD”是动态的,并且您不知道它将具有什么值,在这种情况下,使用正则表达式会更好。 Please see below code snippet: 请参见下面的代码片段:

String value = "161207CAD140000,0";
String patt = "[\\d,]+";
Pattern pattern = Pattern.compile(patt);
Matcher matcher = pattern.matcher(value);

while(matcher.find()){

    System.out.println(matcher.group());
}

If any question let me know in comments. 如果有任何问题,请在评论中让我知道。 Hope it helps. 希望能帮助到你。

This would do the job for any string. 这将完成任何字符串的工作。

String value = "161207CAD140000,0";
String searchedString = "CAD"
int firstIndex = value.indexOf(searchedString);
int lastCharIndex = firstIndex + searchedString.length();

There are methods in the String class for such requirements. 有在这样的要求String类的方法。 You can use the indexOf and lastIndexOf methods to get the positions. 您可以使用indexOf和lastIndexOf方法来获取位置。 eg 例如

int index = value.indexOf("C"); //This returns 6
int lastIndex = value.lastIndexOf("D"); //this returns 8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM