1. 程式人生 > >String類的常用方法,實現首字母大寫(重要),轉換大小寫,判斷字串是否由數字組成,字串與字元陣列的轉換

String類的常用方法,實現首字母大寫(重要),轉換大小寫,判斷字串是否由數字組成,字串與字元陣列的轉換

(1)String類的常用方法:


示例:觀察Public char charAt(int index)


public class Test {


public static void main(String[] args) {
// TODO Auto-generated method stub
String str="hellw";
System.out.println(str.charAt(1));


}


}
結果:e
示例:字串與字元陣列的轉換


public class Test {


public static void main(String[] args) {
// TODO Auto-generated method stub
String str="hellw";
 //將字串變為字元
char data[]=str.toCharArray();
for(int x=0;x<data.length;x++)
{
//轉成大寫字母
data[x]-=32;
System.out.print(data[x]+",");

}
System.out.println(new String(data));//全部轉換字串
System.out.println(new String(data,1,2));//部分轉換字串
}


}
結果:
H,E,L,L,W,HELLW
EL




示例:判斷字串是否由數字組成
public class Test {


public static void main(String[] args) {
// TODO Auto-generated method stub
String str="12w345";
System.out.println(isNumber(str)?"有數字組成":"不是全由數字組成");
}
//如果方法的返回型別是Boolean型別,一般用isXXX()形式命名
public static boolean isNumber(String str)
{
char data[]=str.toCharArray();//將字串變為字元陣列
for(int x=0;x<data.length;x++)
{
if(data[x]<'0'||data[x]>'9')
{
return false;
}


}
return true;//如果都沒有錯誤,返回true
}
}
結果:不是全由數字組成


(2)其他方法
示例:轉換大小寫


public class Test {


public static void main(String[] args) {
// TODO Auto-generated method stub
String str="Sgdfcd";
System.out.println(str.toLowerCase());
System.out.println(str.toUpperCase());
}



}
結果:
sgdfcd
SGDFCD




示例:實現首字母大寫(重要)
public String substring(int beginIndex, int endIndex)表示輸出從下標beginIndex到下標endIndex的字串
public String substring(int beginIndex)表示輸出從下標beginIndex到結尾






public class Test {


public static void main(String[] args) {
// TODO Auto-generated method stub
String name="smith";

System.out.println(initcap(name));
}


public static String initcap(String str)
{
if(str==null||" ".equals(str))//如果沒有資料
{
return str;//直接返回,不做改變

}
if(str.length()>1)
{
return str.substring(0, 1).toUpperCase()+str.substring(1);

}
return str.toUpperCase();
}
}
結果:Smith