Reputation: 35
Im currently working on a String parsing function and suddenly i found this problem. For example:
String data = "1234567890JOHN F DOE";
String ID = data.substring(0,9);
String Name = data.substring(10, 19);
the expected output I want for ID is "1234567890"
however
the only characters I got is only "123456789"
and "0"
is removed.
Are there any function I can use instead of substring(...)
?
Upvotes: 2
Views: 115
Reputation: 641
Let's understand the startIndex and endIndex you need to do this by the code :
String data = "1234567890JOHN F DOE";
String ID = data.substring(0,10);
String Name = data.substring(10, 20);
System.out.println("ID:" + ID);
System.out.println("Name: "+ Name);
Output:
ID: 1234567890
Name: JOHN F DOE
Upvotes: 0
Reputation: 12819
As said in the docs the substring(...)
's ending index is the index inputted minus one. What you want to do is have:
String data = "1234567890JOHN F DOE";
String ID = data.substring(0,10);
String Name = data.substring(10, 20);
Output:
ID: 1234567890
Name: JOHN F DOE
Upvotes: 3
Reputation: 31
you get "123456789"
because the end parameter in the substring(...)
method is not inclusive, so in order to get "1234567890"
you need to use data.substring(0,10)
:)
Upvotes: 3
Reputation: 1112
Using substring you can simply do : str.substring (0,10); This is another way :
String pattern="\\d+";
String text="1234567890JOHN F DOE";
Pattern p=Pattern.compile(pattern);
Matcher m=p.matcher(text);
while (m.find()) {
System.out.println(text.substring(m.start(), m.end()));
}
Upvotes: 0