JavaString类对象的常用方法

①、字符串的连接

public String concat(String str)


该方法类似“+”运算,其参数为一个String类对象,作用是将参数中的字符串str连接到当前字符串的后面。
举例如下:
 

String str ="Hello " ;
str =str.concat("World");//与str+"World"等价 
System.out.println(str); // Hello World

②求字符串的长度。

public int length()


该方法返回字串的长度,这里的长度指的是字符串中Unicode字符的数目。举例如下:
 

String str="Hello World";
System.out.println(str.length()); //输出长度为11

③求字符串中某一位置的字符。

public char charAt(int index)


该方法在一个特定的位置索引一个字符串,以得到字符串中指定位置的字符。值得注意的是,在字符串中第一个字符的索引是0,第二个字符的索引是1,以此类推,最后一个字符的索引是length()-1。

④从字符串中提取子串。

利用String类提供的substring方法可以从一个大的字符串中提取一个子串,该方法有两种常用的形式:

public String substring(int beginIndex)


该方法从beginIndex位置起,从当前字符串中取出剩余的字符作为一个新的字符串返回

public String substring(int beginIndex,int endIndex)


该方法从当前字符串中取出一个子串,该子串从beginIndex位置起至endIndex-1为束。子串返回的长度为endIndex-beginIndex。举例如下:
 

public class TestString{

    public statie void main(String[ ] args){
         String sl="中国重庆",s2;
         s2=sL:
         System.out.println(sl.charAt(1)); //输出:国 
         s2 =sl.substring(2);
         System.out.println(s2); //输出:重庆 
         s2=s1.substring(1,4);
         System.out.println(s2); //输出:国重庆
    }
}

判断字符串的前缀是否为指定的字符串可利用String类提供的下列方法:

public boolean startsWith( String prefix)


该方法用于判断当前字符串的前缀是否和参数中指定的字符串prefix一致。如果是,返回 tnue,否则返回false。

public boolean startsWith( String prefix,int toffset)


该方法用于判断当前字符串从toffset位置开始的子串的前缀是否和参数中指定的字符串 peefx 一致。如果是,返回true,否则返回false。
举例如下:
 

public class Test{
    public static void main(String[] args){
        String s1="电子信息工程学院软件技术专业"; 
        if(s1.startsWith("电子信息工程学院")){
            System.out.println("此学生归电子信息工程学院管理"); 
            if(s1.startsWith("软件技术专业",8)){
                System.out.println("此学生是软件技术专业");
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值