Click to See Complete Forum and Search --> : working with strings


sam_ccld
December 23rd, 2002, 03:28 PM
Hi
I am fairly new to java, I 've got some background in visual basic
there is two function that I used a lot in VB
Left(String, Integer) to remove a number of characters from the left of a string
Ex: Left("Hello", 2)will give "He"
Right(String, Integer) to remove a number of characters from the right of a string
Ex : Right("Hello", 2) will give "lo"
I came up with this two methods in Java to deal with this

public String left(String s, int len) {
StringBuffer str= new StringBuffer("");
for (int j = 0;j < len;j++) {
str.append(s.charAt(j));
}
return str.toString();
}
public String right(String s, int len) {
StringBuffer str = new StringBuffer("");
for (int j = s.length()-len;j < s.length();j++) {
str.append(s.charAt(j));
}
return str.toString();
}


Question :
Is There a proper method In java tha really deals with this issue or shall I stick to my methods thank you

dlorde
December 23rd, 2002, 03:49 PM
When you want to find out what you can do with a class, look at the JavaDocs first. It will save you wasting time reinventing the wheel. If you look at the String (http://java.sun.com/j2se/1.4/docs/api/java/lang/String.html) class, you'll find plenty of useful methods, including two flavours of substring(...) (http://java.sun.com/j2se/1.4/docs/api/java/lang/String.html#substring(int,%20int)).