Useful methods of String and String Builder classes
- The StringBuilder and StringBuffer classes are identical except that StringBuffer is for threaded applications. Use StringBuilder normally, it will be faster.
- All three of these classes are in the java.lang package http://docs.oracle.com/javase/6/docs/api/java/lang/package-summary.html
Method Name | Description | String Class | StringBuffer/ String Builder |
---|---|---|---|
append(str2) | appends str2 to string | ✗ | ✓ |
capacity | # of character spaces allocated | ✗ | ✓ | charAt(n) | returns the letter at position n | ✓ | ✓ |
compareTo(str2) | determines order of string 0=identical, -ve = str1 is first, +ve=str2 is first |
✓ | ✗ |
compareToIgnoreCase | ✓ | ✗ | concat | normally use + operator instead | ✓ | ✗ |
contains(str2) | true if string contains str2 | ✓ | ✗ |
copyValueOf(char[]) | changes char array to a string | ✓ | ✗ | delete (int,int) | ✗ | ✓ |
deleteCharAt | ✗ | ✓ | |
endsWith | - see startsWith - | ✓ | ✗ |
ensureCapacity | ✗ | ✓ | |
equals(str2) | true if str2 == str1 | ✓ | ✗ |
equalsIgnoreCase | ✓ | ✗ | |
getChars | ✗ | ✓ | insert(n, arg) | converts arg to string and insert at n | ✗ | ✓ |
indexOf('c') indexOf(substr) indexOf(str1,n) location of first 'c' in string |
start of substr. -1 if not found first location after n | ✓ | ✓ |
lastIndexOf | - same as indexOf, but starts from end. | ✓ | ✓ |
length() | # of characters in string | ✓ | ✓ |
regionMatches | ✓ | ✗ | |
replace(c1,c2) | replaces characters or strings | ✓ | ✓ |
replaceAll | ✓ | ✗ | |
reverse | ✗ | ✓ | |
setCharAt(n,'c') | sets position n to char c | ✗ | ✓ |
setLength(n) | set length of buffer | ✗ | ✓ |
split | -- complicated - (see next page) | ✓ | ✗ |
startsWith(substr) | returns true if string starts with substr | ✓ | ✗ |
substring(n) substring(p,q) |
returns everything from n onwards returns everything between p and q |
✓ | ✓ |
toCharArray | converts string to array of chars | ✓ | ✗ |
toLowerCase | ✓ | ✗ | |
toUpperCase | ✓ | ✗ | |
toString | ✓ | ✓ | |
trim() | trims whitespace off both ends | ✓ | ✗ |
valueOf(...) | converts number to string | ✓ | ✗ |
Note that these are just the most common String/StringBuilder methods.
Please see the string algorithm page for useful algorithms that use these methods.