字符串数组
1.
String[] week =new String[7];//创建一个长度为7的String(字符串)型的一维数组
week = new String[]{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
2.
String[] week = {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
java数组里面存的是对象的引用,所以必须初始化才能用;
String[] week = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; 这种形式叫数组初始化式(ArrayInitializer),只能用在声明同时赋值的情况下。
如:String[] str = {“1″,”2″,”3”}; // 正确的
String[] str = new String[]{“1″,”2″,”3”} // 也是正确的
而String[ ] str;
str = {“1″,”2″,”3”}; // 编译错误
因为数组初始化式只能用于声明同时赋值的情况下。
String[] week =new String[7];//创建一个长度为7的String(字符串)型的一维数组
week = new String[]{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};是一般形式的赋值,
改为:
String[] str;
str = new String[] {“1″,”2″,”3”}; // 正确了
又如:
void f(String[] str) {
}
f({“1″,”2″,”3”}); // 编译错误
正确的应该是:
f(new String[] {“1″,”2″,”3”});
还可以 String s=new String[30];
如果没有显式赋值,则系统自动赋默认值null。
字符数组赋值
字符串数组不能用"="直接赋值, 即s="Good News!"是不合法的
char s[30];
strcpy(s, "Good News!"); /*给数组赋字符串*/
字符串转换为数字
public class StringToNumber {
public static void main(String[] args) {
String str = "123456";
Integer num1 = new Integer(str);
int num2 = (str);
Integer num3 = (str);
(num1+"\t"+num2+"\t"+num3);
}
百分比输出
//获取格式化对象 NumberFormat nt = (); //设置百分数精确度2即保留两位小数 (2); //最后格式化并输出 ("百分数:" + (percentage));
字符串遍历
for(int i = 0; i < (); i++) {
char letter = (i);
(letter);
}
可以将任何字符串转换为字符数字,再用改进的for循环来迭代:
for (char letter:()){
(letter);
}