/* |A |BB |CCC |
|1 |22 |33333 |
|aaa1111 |bbbb222 |ccc333 |*/
String format = "|%1$-10s|%2$-10s|%3$-20s|\n"; System.out.print(String.format(format,"A", "BB", "CCC"));
System.out.format(format, "1", "22", "33333");
System.out.format(format, "aaa1111", "bbbb222", "ccc333");
//2011:08:30
System.out.println(String.format("%1$tY:%1$tm:%1$te", Calendar.getInstance()));
//|1111 |
System.out.println(String.format("|%1$-10s|","1111"));
//| 1111|
System.out.println(String.format("|%1$-10s|","1111"));
//| 1111|
System.out.println(String.format("|%1$#10s|","1111"));
// true
String phone = "111-111-1111";
String phoneNumberPattern = "(\\d{3})?(\\d{2})?-\\d{3}-\\d{4}";
System.out.println(phone.matches(phoneNumberPattern));
// true
String date = "12-12-2012";
String datePattern = "\\d{2}-\\d{2}-\\d{4}";
System.out.println(date.matches(datePattern));
// true
// true
String zip = "1234-12351";
String zipCodePattern = "\\d{4}(-\\d{5})?";
System.out.println(zip.matches(zipCodePattern));
//A bubble sort for String array
public static String[] bubbleSort(String[] stringAtt) {
String[] arr = stringAtt;
for (int j = 0; j < arr.length; j++) {
for (int i = j + 1; i < arr.length; i++) {
if (arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
}
return arr;
}
//Collapse multiple spaces
public static String collapseMultipleSpaces(String str) {
char last = str.charAt(0);
StringBuffer argBuf = new StringBuffer();
for (int cIdx = 0; cIdx < str.length(); cIdx++) {
char ch = str.charAt(cIdx);
if (ch != ' ' || last != ' ') {
argBuf.append(ch);
last = ch;
}
}
return argBuf.toString();
}
// 12987
System.out.println("ab1 2c9_8z yx7".replaceAll("\\D", ""));
// ab c_z yx
// ab c_z yx
System.out.println("ab1 2c9_8z yx7".replaceAll("\\d", ""));
No comments:
Post a Comment