JAVASE的学习笔记(六)字符串

字符串

Java设计当中字符串是一个很特殊的类(包装类),String本身特殊引用数据类型
str默认不是null,是空:“”

String的实例化方式

str是一个对象,因为可以通过它调用方法(行为)

  • 个人推荐:直接方式赋值字符串,那么就对String类进行了实例化和初识操作
  • String提供的构造方法,请注意重载了很多的构造方法,之后使用有很帮助,但是个人不推荐使用构造方法创建

特殊性:String不可变

在这里插入图片描述

源码:

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];
  • String是final 修饰的,是不可以被继承使用
  • 字符串的底层使用是通过字符数组存储char value[];
  • 该字符数组使用final修饰,因为地址值是不可以变的,数组长度固定final char value[]

字符串比较

  • “==”比较地址
  • equals()比较内容:源码中重写了该方法

源码

 public boolean equals(Object anObject) {//s2 :  String->对象上转型->Object
        if (this == anObject) {// false
            return true;
        }
        if (anObject instanceof String) {//必须判断类类型
            String anotherString = (String)anObject;//强类型转换
            int n = value.length;//s1字符数组长度
            if (n == anotherString.value.length) {//s2字符数组的长度比较
                char v1[] = value;//s1字符数组
                char v2[] = anotherString.value;//s2字符数组
                int i = 0;//索引
                while (n-- != 0) {
                    if (v1[i] != v2[i])//字符比较(整数的比较)
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

字符串方法

(1)字符串和字符相关方法
  • 字符数组通过构造方法转换为字符串
    String(char[] value, int offset, int count):从索引offset开始,输出长度为count的字符串转字符数组
    char charAt(int index) :取得指定索引位置的字符,索引从0开始。
    char[] toCharArray() :将字符串转换为字符数组
(2)字符串和字节相关方法
public class Demo07{
    public static void main(String...args)throws Exception{
       byte[] arr01 = {97,32,99,65,66,67};
       String s1 = new String(arr01);
       System.out.println(s1);
       String s2 = new String(arr01,2,3);
       System.out.println(s2);
       //编码
       String s3 = new String(arr01,"US-ASCII");
       System.out.println(s3);
       
       System.out.println("============字符串转byte数组===================");
       //案例:大小写转换
       String str = "welcomeonestep";
       byte[] arr02 = str.getBytes();
       for(byte b : arr02){
           System.out.print(b+"\t");
       }
       System.out.println("===>使用普通for循环,索引");
       for(int i=0;i<arr02.length;i++){
           arr02[i]-=32;
       }
       String s4 = new String(arr02);
       System.out.println(s4);
       
        
    }
}
  • 大小写转换:toLowerCase():转小写  toUpperCase():转大写
  • 获取字符串的长度:底层就是获取字符数组的长度System.out.println(str.length());
(3)字符串查找
public class Demo09{
    public static void main(String...args)throws Exception{ 
       String str = "welcomeonestep";
       
       System.out.println("contains:boolean=>是否包含你要查找的内容=>个人不推荐");
       boolean f1 = str.contains("one");
       System.out.println(f1);
       System.out.println(str.contains("abcdef"));
       System.out.println("====>推荐查找方式:");
       
       System.out.println("indexOf:int=>从0开始找的索引位置,如果没有找到返回-1");
       int index = str.indexOf("come");
       System.out.println(index);
       index = str.indexOf("come",4);
       System.out.println(index);
       
       System.out.println("lastIndexOf:int=>从length()-1开始向前找的索引位置,如果没有找到返回-1");
       index = str.lastIndexOf("come");
       System.out.println(index);
       index = str.lastIndexOf("one",7);
       System.out.println(index);
       
       System.out.println("必须是0的位置匹配:");
       f1 = str.startsWith("come");
       System.out.println(f1);
       f1 = str.startsWith("welcome");
       System.out.println(f1);
       System.out.println("从后匹配:");
       f1 = str.endsWith("pets");
       System.out.println(f1);//false
       f1 = str.endsWith("step");
       System.out.println(f1);//true
       
    }
}
(4)字符串截取
public class Demo09{
    public static void main(String...args)throws Exception{ 
       String str = "welcomeonestep";
       
       System.out.println("=>得到一个新的字符串,原来的字符串不变");
       String s1 = str.substring(2);//从索引位置截取到末尾
       System.out.println(s1);
       System.out.println(str);
       
       System.out.println("=>截取指定的内容");
       String s2 = str.substring(3,7);//[3,7)
       System.out.println(s2);
        
    }
}
(5)字符串替换
public class Demo10{
    public static void main(String...args){ 
       String str = "welconmeonestep";
       
       System.out.println("=>得到一个新的字符串,原来的字符串不变");
       String s1 = str.replace('e','你');//按照字符替换,不喜欢
       System.out.println(s1);
       System.out.println(str);
       String s2 = str.replace("on","我们");
       System.out.println(s2);
       String s3 = str.replaceFirst("on","我们");
       System.out.println(s3);
       System.out.println("replaceAll替换全部,支持正则表达式");
       
       String s4 = "2019年02月17日";//2019-02-17
       String s5 = s4.replace("年","-");
       s5 = s5.replace("月","-");
       s5 = s5.replace("日","");
       System.out.println(s5);
       //网页爬虫会大量的使用正则表达式
       String s6 = s4.replaceAll("年|月|日","-");
       System.out.println(s6);
       
       
    }
}
(6)字符串分割
public class Demo11{
    public static void main(String...args){ 
       String str = "100,20,50,77,88";
       
       System.out.println("=>分割成数组");
       //也支持正则表达式
       String[] arr = str.split(",");
       for(String s:arr){
           System.out.println(s);
       }

    }
}
(7)字符串的去掉两端空格
public class Demo01{
    public static void main(String...args){
       String str = "     西   游   记     ";
       System.out.println("=="+str+"==");
       String s1 = str.trim();//去掉两端空格
       System.out.println("=="+s1+"==");
       //问题1:如何完成去掉全部空格?
       String s2 = str.replaceAll(" ","");
       System.out.println("=="+s2+"==");
       //也是应该使用正则表达式完成
       //使用数组解决
       
       //问题2:如何完成去掉左侧空格?
       char[] arr01 = str.toCharArray();
       int index = -1;
       for(int i=0;i<arr01.length;i++){
           if(arr01[i]!=' '){
               index = i;
               break;
           }
       }
       String s3 = str.substring(index);
       System.out.println("=="+s3+"==");
         
       //问题3:如何完成去掉右侧空格?
       index = -1;
       for(int i=arr01.length-1;i>=0;i--){
           if(arr01[i]!=' '){
               index = i;
               break;
           }
       }
       String s4 = str.substring(0,index+1);
       System.out.println("=="+s4+"==");
    }
}
(8)如何判断字符串为空

1.对象存在
2.对象不存在
3.全是空格

public class Demo02{
    public static void main(String...args){
       //中文:空(""或者null) 包含了很多意思
       String s1 = "";//字符串对象是存在的,可以调用方法
       System.out.println(s1.equals(""));
       System.out.println(s1.length()==0);
       System.out.println(s1.isEmpty());
       
       System.out.println("=======null:不存在==========");
       String s2 = null;//对象不存在,无法调用方法
       System.out.println(s2==null);
       //System.out.println(s2.length());
       //System.out.println(s2.isEmpty());
       
        System.out.println("=======\"            \"==========");
        String s3 = "            ";//对象存在,我认为也是空
        System.out.println(s3.equals(""));
        System.out.println(s3.length()==0);
        System.out.println(s3.isEmpty());
    }
}

将上述代码简单封装:

public class Demo03{
    public static void main(String...args){
       //中文:空(""或者null) 包含了很多意思
       String s1 = "";//字符串对象是存在的,可以调用方法
       System.out.println(isBlank(s1));

       
       System.out.println("=======null:不存在==========");
       String s2 = null;//对象不存在,无法调用方法
       System.out.println(isBlank(s2));
       
        System.out.println("=======\"            \"==========");
        String s3 = "            ";//对象存在,我认为也是空
       System.out.println(isBlank(s3));
    }
    
    public static boolean isBlank(String str){
        if(str!=null){
            return str.trim().length()==0;
        }
        return true;
    }
}
(9)字符串拼接

将数组{100,200,300,400,500}转化为 “100#200#300#400#500”

public class Demo04{
    public static void main(String...args){
        int[] arr = {100,200,300,400,500};
        //得到一个字符串String的内容是以下的形式 “100#200#300#400#500”
        System.out.println(m1(arr));
        System.out.println(m2(arr));
        
        
    }
    
    public static String m1(int[] array){
        String str = "";
        for(int i=0;i<array.length;i++){
            if(i==array.length-1){
                str+=array[i];
            }else{
                str+=array[i]+"#";
            } 
        }
        return str;
    }
    public static String m2(int[] array){
       String str = "";
        for(int i=0;i<array.length;i++){ 
           str+=array[i]+"#";
        } 
        str = str.substring(0,str.length()-1);
        return str;
    }
}

这种字符串拼接方法在常量池中开辟太多无用空间,影响效率

面试题:StringBuffer和StringBulider区别

StringBuffer:使用同步关键字synchronized的修饰,所以线程安全,导致效率比较低

StringBulider:没有使用同步关键字的修饰,所以线程不安全,但是效率高(一般推荐使用StringBulider

import java.awt.*;
import java.math.BigDecimal;
import java.util.Arrays;

public class F04 {
    public static void main(String[] args) {
        int[] arr = {100,200,300,400,500};
        StringBuilder builder = new StringBuilder();
        m1(builder,arr);
        System.out.println(builder);

    }
    public static void m1(StringBuilder builder,int[] arr){
        for(int num : arr){
            builder.append(num);
            builder.append("#");
        }
        builder.deleteCharAt(builder.length()-1);//关键
    }
}

在此方法中,常量池仅开辟了 builder.append("#")一个空间,即完成功能。

个人推荐:还是推荐使用+拼接字符串,JDK8之后底层拼接实际上使用StringBuilder

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

月色夜雨

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

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

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

打赏作者

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

抵扣说明:

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

余额充值