Wednesday, January 30, 2008

java strings

Strings (java.lang)

Constructing a String

If you are constructing a string with several appends, it may be more efficient to construct it using a StringBuffer and then convert it to an immutable String object.

StringBuffer buf = new StringBuffer("Initial Text");

// Modify

int index = 1;

buf.insert(index, "abc");

buf.append("def");

// Convert to string

String s = buf.toString();

Getting a Substring from a String

int start = 1;

int end = 4;

String substr = "aString".substring(start, end); // Str

Searching a String

String string = "aString";

// First occurrence.

int index = string.indexOf('S'); // 1

// Last occurrence.

index = string.lastIndexOf('i'); // 4

// Not found.

index = string.lastIndexOf('z'); // -1

Replacing Characters in a String

// Replace all occurrences of 'a' with 'o'

String newString = string.replace('a', 'o');

Replacing Substrings in a String

static String replace(String str,

String pattern, String replace) {

int s = 0;

int e = 0;

StringBuffer result = new StringBuffer();

while ((e = str.indexOf(pattern, s)) >= 0) {

result.append(str.substring(s, e));

result.append(replace);

s = e+pattern.length();

}

result.append(str.substring(s));

return result.toString();

}

Converting a String to Upper or Lower Case

// Convert to upper case

String upper = string.toUpperCase();

// Convert to lower case

String lower = string.toLowerCase();

Converting a String to a Number

int i = Integer.parseInt("123");

long l = Long.parseLong("123");

float f = Float.parseFloat("123.4");

double d = Double.parseDouble("123.4e10");

Converting Unicode to UTF-8

try {

String string = "\u5639\u563b";

byte[] utf8 = string.getBytes("UTF8");

} catch (UnsupportedEncodingException e) {

}

Converting UTF-8 to Unicode

public static String toUnicode(byte[] utf8buf) {

try {

return new String(utf8buf, "UTF8");

} catch (UnsupportedEncodingException e) {

}

return null;

}

Determining a Character's Unicode Block

char ch = '\u5639';

Character.UnicodeBlock block =

Character.UnicodeBlock.of(ch);

Breaking a String into Words

String aString = "word1 word2 word3";

StringTokenizer parser =

new StringTokenizer(aString);

while (parser.hasMoreTokens()) {

processWord(parser.nextToken());

}

No comments: