Is there any string function in Java that will allow me to extract the substring like QString::mid:
http://doc.qt.io/qt-5/qstring.html#mid
When index exceeds string length, I want the function to return empty string, and when index+length of substring is greater, I want the function to return only available characters.
I have written piece of code that does it, but I refuse to believe such fuction is not in Java already:
private static String Mid(String s, int index, int length){
if(s.length()>=length+index){
return s.substring(index, length+index);
}
else if(s.length()>=index) {
return s.substring(index, s.length());
}
else{
return "";
}
}
Is there something like this in Java?
It sounds like you just need Math.min
a couple of times:
int start = Math.min(index, s.length());
int end = Math.min(index + length, s.length());
return s.substring(start, end);
See more on this question at Stackoverflow