Reputation: 15
I am trying to solve this in Java. I have a long string of information and I want to split the string based on the length of the fields given.
Example: `FirstNameLastName yy-mm-dd549Eastwolframstreet
I have a list of fields given along with its length. There are n number of fields. example fields:
If the name is less than 9 characters spaces occupy the remaining positions. i.e Lastname is length 9 but there are only 8 letters remaining one is a space.
What is the best way to extract those fields from each of its given length?
Upvotes: 0
Views: 118
Reputation: 8466
Try this,
String value = "FirstNameLastName yy-mm-ddAddress FirstNameLastName yy-mm-ddAddress FirstNameLastName yy-mm-ddAddress ";
for (int i = 0; i < value.length(); i++)
{
System.out.println("First Name : "+value.substring(i, i + 9));
System.out.println("Last Name : "+value.substring((i + 9), i + 18));
System.out.println("Date : "+value.substring(i + 18, i + 26));
System.out.println("Address : "+value.substring(i + 26, i + 56));
i = i + 55;
}
Upvotes: 1
Reputation: 20163
Knowing that each part is an exact length--and if it happens to be less, it's padded by spaces--this is a perfect situation for using String.substring(i,i)
and String.trim()
.
For example: str.substring(0, 9)
is the first nine characters. Now trim it, and any extra pad-spaces will be eliminated.
Upvotes: 1