Java学习预科(三)——字符串

返回目标字串出现的次数

class note{
    public static int get(String str,String key){
        int count=0;
        int index=0;
        while((index=str.indexOf(key))!=-1){
            str=str.substring(index+key.length());
            count++;
        }
        return count;
    }
    public static void main(String args[]){
        String str="abcdkkskkdkkfkk";
        System.out.println("count"+get(str,"kk"));
    }
}

返回两个字符串中最大相同字串

class note{
    public static String getMax(String s1, String s2){
        String max="",min="";
        max=(s1.length()>s2.length())?s1:s2;
        min=(max==s1)?s2:s1;
        for(int x=0;x<min.length();x++){
            for(int y=0,z=min.length()-x;z!=min.length()+1;y++,z++){
                String temp=min.substring(y,z);
                if(max.contains(temp))
                    return temp;
            }
        }
        return "";
    }
    public static void main(String args[]){
        String s1="abchellodef";
        String s2="ahellob";
        System.out.println(getMax(s1,s2));
    }
}

StringBuffer是一个字符串缓冲区
是一个容器而且长度是可变化的;可以直接操作多个数据类型;最终会通过toString方法变成字符串

1.存储
StringBuffer append():将指定数据作为参数添加到已有数据结尾处
StringBuffer insert(index,数据):可以将数据插入到指定index位置
2.删除
StringBuffer delete(start,end):删除缓冲区中的数据,可以指定开始和结束的位置
StringBuffer deleteCharAt(index):删除指定位置的数据
3.获取
4.修改
StringBuffer setCharAt(index,数据)

class note{
    public static void main(String[] args) {
        method_add();
        method_delete();
        method_update();
    }
    public static void method_add(){
        StringBuffer sb=new StringBuffer();
        sb.append("abc").append(true);
        sb.insert(1,"insert");
        System.out.println(sb.toString());
    }
    public static void method_delete(){
        StringBuffer sb=new StringBuffer("abc");
        sb.delete(1,2);//sb.deleteCharAt(1);
        System.out.println(sb.toString());
    }
    public static void method_update(){
        StringBuffer sb=new StringBuffer("abc");
        sb.setCharAt(1,'k');
    }
}

JDK1.5版本之后出现了StringBuiled,StringBuffer是线程安全的,StringBuiled是线程不安全的
单线程建议使用StringBuiled提高效率,多线程使用StringBuffer


基本数据类型对象包装类

基本数据类型引用对象
byteByte
shortshort
intInteger
longLong
charCharacter

最常见的作用:就是用基本数据类型和字符串类型之间做转换

基本数据类型转成字符串

  • 基本数据类型+“”
  • 基本数据类型.toString(基本数据类型)

字符串传成基本数据类型

  • int num=Integer.parseInt(字符串类型)
class note{
    public static void main(String[] args) {
        //Integer x=new Integer(4);
        Integer x=4;//JDK1.5之后新特性//自动装箱
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星辰引路-Lefan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值