Mohamed Nagy
Mohamed Nagy

Reputation: 176

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.

Upvotes: 3

Views: 19327

Answers (3)

knaos
knaos

Reputation: 850

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();

Upvotes: 3

SachinSarawgi
SachinSarawgi

Reputation: 2692

You can use String.indexOf(String str) function which will return starting indexof the "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".

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. 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.

Upvotes: 6

jaletechs
jaletechs

Reputation: 571

There are methods in the String class for such requirements. You can use the indexOf and lastIndexOf methods to get the positions. e.g

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

Upvotes: 1

Related Questions