java String操作
package shaohv.String;
import java.util.Formatter;
public class StringInit {
//for 1.
public static String upcase(String s){
return s.toUpperCase();
}
//for 2.
public static void change(String s){
s = "changing";
System.out.println("in change String is: "+s);
}
//for 4.
class Receipt{
private double total = 0;
private Formatter f = new Formatter(System.out);
public void printTitle(){
f.format("%-15s %5s %10s\n", "Term","Qty","Price");
f.format("%-15s %5s %10s\n", "----","---","-----");
}
public void myprint(String name, int qty, double price){
f.format("%-15.15s %5d %10.2f", name,qty,price);
}
}
public static void main(String[] args){
/*
* 1. 测试一下声明与初始化的关系
* 结果说明:String可以先声明,然后再初始化
*/
System.out.println("\n1、***********************************");
String a = "hello";
String b = null;
System.out.println("String a is: "+a);
System.out.println("String b is: "+b);
a = "world";
b = "what";
System.out.println("String a is: "+a);
System.out.println("String b is: "+b);
/*
* 2. 测试一下String的不可变性
* 结果说明: String类型是不可变的,自己体会一下。
*/
System.out.println("\n2、***********************************");
String c = "okay";
String d = "good";
System.out.println("before upcase c is: "+c);
String cc = upcase(c);
System.out.println("cc is: "+cc);
System.out.println("after upcase c is: "+c);
System.out.println("before change d is: "+d);
change(d);
System.out.println("after upcase d is: "+d);
/*
* 3. 格式化输出System.out.format
*/
System.out.println("\n3、***********************************");
int e = 20974 ;
float f = 34345.7234f;
double g = 3.1215926d;
System.out.format("row 1: [%d,%f,%f]\n", e,f,g);
System.out.printf("row 2: [%d,%f,%f]\n", e,f,g);
/*
* 4. Formatter类
*/
System.out.println("\n4、***********************************");
StringInit stringInit = new StringInit();
Receipt receipt = stringInit.new Receipt();
receipt.printTitle();
receipt.myprint("jack is my friend", 4, 3.1415926);
/*
* 5. String.format接受与Formatter.format同样的参数
* 输出一个String对象
*/
System.out.println("\n5、***********************************");
String h = String.format("(t%d,q%d) %s",3,7,"write failed!" );
System.out.println(h);
}
}
结果输出:
1、*********************************** String a is: hello String b is: null String a is: world String b is: what 2、*********************************** before upcase c is: okay cc is: OKAY after upcase c is: okay before change d is: good in change String is: changing after upcase d is: good 3、*********************************** row 1: [20974,34345.722656,3.121593] row 2: [20974,34345.722656,3.121593] 4、*********************************** Term Qty Price ---- --- ----- jack is my frie 4 3.14 5、*********************************** (t3,q7) write failed!

浙公网安备 33010602011771号