I am a Java developer but I need a code to be converted from PHP to Java. I need a function which gives equivalent result in Java as of PHP fuction substr (as Java doesn't take negative values whereas php takes).
For example:
$string = "I am not lonely man";
$sub = $substr($string,1,-3);
EDIT: PROPER ANSWER:-
public String substr(String string,int from,int to){
if(from < 0 && to < 0){
if(Math.abs(from) > Math.abs(to)){
String s = string.substring(string.length()-Math.abs(from));
return s.substring(s.length()-Math.abs(to));
}else{
return "";
}
}else if(from >= 0 && to < 0){
String s = string.substring(from);
if(Math.abs(to) >= s.length()){
return "";
}else{
return s.substring(0,s.length()-Math.abs(to));
}
}else if(from < 0 && to >= 0){
String s = string.substring(string.length()-Math.abs(from));
if(to >= s.length()){
return s;
}
return s.substring(0,to);
}else{
String s = string.substring(Math.abs(from));
if(to >= s.length()){
return s;
}else{
return s.substring(0, Math.abs(to));
}
}
}
Output: am not lonely
It's relatively easy to calculate this yourself, but if you want handy methods for this sort of thing, consider using Apache StringUtils.