Is there an easy way to trim a String based on his Offset and Count values, that is, a function that returns OO
for a String FOOBAR
with an offset
of 1 and a count
of 2?
Obvious, one could write a simple function for this task, but I wonder if their is not a predefined Java functionality for this?
//edit: To clearify: I do mean the offset
and count
values defined within the given String
, not external Integer
values.
EDIT: Okay, now you've made your question clearer, it sounds like this is the scenario you're talking about, and the solution using the String(String)
constructor:
// offset = 0, count = 6, backing array = { 'F', 'O', 'O', 'B', 'A', 'R' }
String original = "FOOBAR";
// offset = 1, count = 2, backing array = { 'F', 'O', 'O', 'B', 'A', 'R' }
String substring = original.substring(2);
// offset = 0, count = 2, backing array = { 'O', 'O' }
String trimmed = new String(substring);
Yup, substring
:
String substring = text.substring(offset, offset + count);
substring
takes two parameters - the "begin index" (inclusive) and the "end index" (exclusive) - hence the addition in the above code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.