不可变String
String对象是不可变的,每一个修改String值得方法,实际上是创建了一个全新的String对象,以包含修改后的字符串对象,而最初的字符串对象没有改变。
public class Immutable {
public static String upcase(String s) {
return s.toUpperCase();
}
public static void main(String[] args) {
String q = "howdy";
System.out.println(q);
String qq = upcase(q);
System.out.println(qq);
System.out.println(q);
}
}/*output
howdy
HOWDY
howdy
*/
把q传给upcase()方法时,实际传递的是一个引用的拷贝,而该引用所指向的对象其实一直待在一个单一的物理位置上,从未动过。
String上的操作
方法 | 作用 |
---|---|
length() | 返回String中字符的个数 |
charAt() | 取得该索引位置上的char |
toCharArray() | 返回String的字符数组 |
contains() | 如果String包含参数内容,则返回true |
indexOf() | 如果String不包含此参数,就返回-1,否则返回此参数在String中的起始索引 |
trim() | 将字符串两端的空白字符删除再返回String |
格式化输出
format()方法可用于PrintStream或者PrintWriter对象,用来控制字符串的输出格式,抽象语法是:%[argument_index$][flags][width][.precision]conversion
public class Receipt {
private double total = 0;
public void printTitle() {
System.out.format("%-15s %5s %10s\n", "Item", "Qty", "Price");
System.out.format("%-15s %5s %10s\n", "----", "---", "-----");
}
public void print(String name, int qty, double price) {
System.out.format("%-15.15s %5d %10.2f\n", name, qty, price);
total += price;
}
public void printTotal() {
System.out.format("%-15s %5s %10.2f\n", "Tax", "", total * 0.06);
System.out.format("%-15s %5s %10s\n", "", "", "-----");
System.out.format("%-15s %5s %10.2f\n", "Total", "", total * 1.06);
}
public static void main(String[] args) {
Receipt receipt = new Receipt();
receipt.printTitle();
receipt.print("Jack's Magic Beans", 4, 4.25);
receipt.print("Princess Peas", 3, 5.1);
receipt.print("Three Bears Porridge", 1, 14.29);
receipt.printTotal();
}
}/*output
Item Qty Price
---- --- -----
Jack's Magic Be 4 4.25
Princess Peas 3 5.10
Three Bears Por 1 14.29
Tax 1.42
-----
Total 25.06
*/
width用于控制一个域的最小尺寸,默认情况下,数据是右对齐,不过可以通过“-”标志改变对齐方向,precision用于指明最大尺寸,应用于String时表示打印输出字符的最大数量,应用于浮点数时表示表示小数部分要显示的位数。
Pattern和Matcher
static Pattern.compile()方法会根据String类型的正则表达式生成一个Pattern对象,然后把想要检索的字符串传入Pattern对象的matcher()方法生成一个Matcher对象,它有很多功能可供使用。
public class TestRegularExpression {
public static void main(String[] args) {
String regex = ".*java$";
String[] strs = {"a.java", "bjava", "c++", "abca"};
Pattern p = Pattern.compile(regex);
for (String str : strs) {
Matcher m = p.matcher(str);
System.out.println(m.matches());
}
}
}/*output
true
true
false
false
*/