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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值