String类

简介: String类

hello,大家好,今天为大家带来String类的相关知识

在C语言中,没有字符串类,在Java中有字符串类,举个例子,String  ret="hello";   这就是一个字符串类型的变量,

下面我们来说一下String 类在创建的时候的三种形式


public class Test {
    public static void main(String[] args) {
        String  string="hello";
        String ret=new String("wyb520");
        char[] ch={'a','b','c'};
        String str=new String(ch);
    }
}


一种是直接写

还有一种是new一个对象

最后一种是通过创建一个数组,然后new一个数组对象

8e7abe2333554a77a0bee53151010c8e.png

6807cd89c8044c3dba77084399e118f9.png


大家看我的这个截图,我们要注意到其实String这个对象在创建一个变量时有value和hash两个内存,我们转到String的源码看一下


bd7e74fe29b648ffb499a0a46ca24048.png


从这个源码当中就可以看出来,有hash和value,value是一个引用


一定有同学对String直接new了一个新对象有疑问,其实真正的原因就是String类继承了object类,object类默认是所有类的父类,所以可以直接new实例化对象


现在用图来更好的理解一下String类的对象的创建


1d1f4202e674403fb1d92cddba637e1d.png


4cfcd5964eee4d17a7c424c4f86ef470.png


string与ret两个变量的创建如上图,比较特殊的是数组那一块,先创建数组然后new  String时拷贝了一份数组。

Java当中没有所谓的\0结尾。

String 是引用类型,内部并不存储字符串,其实字符串保存在数组中


String s1 = new String("hello");
        String s2 = new String("world");
        String s3 = s1;
        System.out.println(s1.length());
        System.out.println(s1.isEmpty());


在计算字符串的长度时一定要.length(),这个括号不能忘


下面继续画图让大家更好的理解这几个对象的创建



e7ba6025c4a94983bd956264f5d88700.png

🐶String字符串的比较


字符串排序。Java中总共提供了4中方式


1.用==来判断. ==比较是否引用同一个对象


对于基本类型,==比较的是变量中的值;对于引用类型==比较的是引用中的地址。


public static void main(String[] args) {
        int a = 40;
        int b = 20;
        int c = 40;
System.out.println(a == b); // false
System.out.println(a == c); // true
    }
 public static void main(String[] args) {
        String s1=new String("wyb");
        String s2=new String("wyb");
        System.out.println(s1==s2);//false
    }


对于这个引用类型

两个变量的地址不一样。所以答案是false


🐷2.用equals方法比较


 public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("hello");
        String s3 = new String("world");
        System.out.println(s1 == s2);   // false
        System.out.println(s1.equals(s2));//true
        System.out.println(s2 == s3);   // false
        System.out.println(s2.equals(s3)); // false
    }


3.使用compare   to


System.out.println(s1.compareTo(s2));
//compaer  to 的源码
 public int compareTo(String anotherString) {
        int len1 = value.length;
        int len2 = anotherString.value.length;
        int lim = Math.min(len1, len2);
        char v1[] = value;
        char v2[] = anotherString.value;
        int k = 0;
        while (k < lim) {
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) {
                return c1 - c2;
            }
            k++;
        }
        return len1 - len2;
    }


compare  to    返回的是int类型的值,看一下源码大家就能 明白了,长度相等返回0,不等返回两长度差值

🐷4.int compareToIgnoreCase


这个函数与compare   to   其实是一样的,就是忽略了大小写


public static void main(String[] args) {
        String s1 = new String("WYB");
        String s2 = new String("wyb");
        System.out.println(s1.compareToIgnoreCase(s2));//0
    }


03c0b5edf17743f1976175de2668b83f.png

String类提供的字符串查找方法


public static void main(String[] args) {
String s = "aaabbbcccaaabbbccc";
System.out.println(s.charAt(3)); // 'b'
System.out.println(s.indexOf('c')); // 6
System.out.println(s.indexOf('c', 10)); // 15
System.out.println(s.indexOf("bbb")); // 3
System.out.println(s.indexOf("bbb", 10)); // 12
System.out.println(s.lastIndexOf('c')); // 17
System.out.println(s.lastIndexOf('c', 10)); // 8
System.out.println(s.lastIndexOf("bbb")); // 12
System.out.println(s.lastIndexOf("bbb", 10));// 3
    }


💚char charAt(int index):返回index位置上字符,如果index为负数或者越界,抛出IndexOutOfBoundsException异常

💚int indexOf(int ch) 返回ch第一次出现的位置,没有返回-1


💚int indexOf(int ch, intfromIndex):从fromIndex位置开始找ch第一次出现的位置,没有返回-1


💚int indexOf(String str) 返回str第一次出现的位置,没有返回-1

💚int indexOf(String str, intfromIndex):从fromIndex位置开始找str第一次出现的位置,没有返回-1

💚int lastIndexOf(int ch) 从后往前找,返回ch第一次出现的位置,没有返回-1

💚int lastIndexOf(int ch, intfromIndex):从fromIndex位置开始找,从后往前找ch第一次出现的位置,没有返回-1

💚int lastIndexOf(String str) 从后往前找,返回str第一次出现的位置,没有返回-1

💚 int lastIndexOf(String str, intfromIndex):从fromIndex位置开始找,从后往前找str第一次出现的位置,没有返回-1


🐷数值和字符串转换


用valueof


 public static void main(String[] args) {
        //把其他的数据类型 变成字符串
        String s = String.valueOf(123);
        String s2 = String.valueOf(12.5);
        System.out.println(s);
        System.out.println(s2);
    }


结果


    public static void main(String[] args) {
        //字符串转数字
        int data1 = Integer.parseInt("199785");
    double data2 = Double.parseDouble("1997.85");
    System.out.println(data1);
    System.out.println(data2);
    }
 public static void main(String[] args) {
        int a = Integer.valueOf("64");//6*8^1 + 4*8^0 = 52//默认十进制
        System.out.println(a);
        int a2 = Integer.parseInt("100");//默认十进制                                                
        System.out.println(a2);
    }
public static void main(String[] args) {
            String s1 = "abondon";
            String ret = s1.toUpperCase();
            System.out.println(ret);
            System.out.println("s1-> " + s1);
            String s2 = "ABANDON";
            ret = s2.toLowerCase();
            System.out.println(ret);
    }


aba54458d07146949dc6f2dc5944ac74.png

这里要注意,使用这个大小写的时候要记得本身并没有改变


   public static void main(String[] args) {
     String s = "happy";
// 字符串转数组
     char[] ch = s.toCharArray();
    for (int i = 0; i < ch.length; i++) {
     System.out.print(ch[i]);
 }
  System.out.println();
// 数组转字符串
  String s2 = new String(ch);
    System.out.println(s2);
    }


格式化


public static void main(String[] args) {
            String s = String.format("%d-%d-%d", 2003 ,2,14);
            System.out.println(s);//2003-2-14
        }
public static void main(String[] args) {
            String s1 = "ababcabcdabcde";
            String ret = s1.replaceFirst("ab","qquuuuu");//代表用qquuuuu替换第一个ab
            System.out.println(ret);
            System.out.println("s1->  "+s1);//就算替换,但是它本身是没有改变的
        }
字符串拆分
public static void main(String[] args) {
            String s1 = "hello wyb happy everyday";
            String[] ret = s1.split(" ",4);//以空格的形式分开,分成4组
            for (String s : ret) {
                System.out.println(s);//打印
            }
        }

bb025e4ee9334dd787de9f70d7a7422f.png


public static void main(String[] args) {
        String str = "192.168.1.1";
        String[] ret = str.split("\\.",4);
        for (String s : ret) {
            System.out.println(s);
        }
    }


5f34c6e8407b4456815129c212c20eea.png


以\.的形式分为4组打印,\需要两条\\来编译,那么两条\\就需要4条\\\\来编译


  public static void main16(String[] args) {
        String str = "197\\168\\1\\1";
        String[] ret = str.split("\\\\");
        for (String s : ret) {
            System.out.println(s);
        }
    }


public static void main(String[] args) {
            String str = "abcdef";
            String ret = str.substring(1,4);//[1,4)//字符串截取//结果为bcd默认范围为左闭右开
            System.out.println(ret);
            System.out.println("=============");
            String s = "    we are happy    ";
            System.out.println(s.trim());//当前字符串的左右的空格去掉
//trim 会去掉字符串开头和结尾的空白字符(空格, 换行, 制表符等).
            System.out.println(s);
    }


字符串替代


public static void main(String[] args) {
        String str="we%are%happy";
        String ret=str.replaceAll("%"," ");
        System.out.println(ret);
    }

用空格替代所有的%

今天的分享就到这里,我们下期再见,886


相关文章
|
8天前
|
Java 索引
java基础(13)String类
本文介绍了Java中String类的多种操作方法,包括字符串拼接、获取长度、去除空格、替换、截取、分割、比较和查找字符等。
21 0
java基础(13)String类
|
2月前
|
API 索引
String类下常用API
String类下常用API
36 1
|
2月前
for循环和String类下方法的一个练习题
for循环和String类下方法的一个练习题
45 1
|
6天前
|
安全 Java
String类-知识回顾①
这篇文章回顾了Java中String类的相关知识点,包括`==`操作符和`equals()`方法的区别、String类对象的不可变性及其好处、String常量池的概念,以及String对象的加法操作。文章通过代码示例详细解释了这些概念,并探讨了使用String常量池时的一些行为。
String类-知识回顾①
|
19天前
|
存储 安全 Java
Java——String类详解
String 是 Java 中的一个类,用于表示字符串,属于引用数据类型。字符串可以通过多种方式定义,如直接赋值、创建对象、传入 char 或 byte 类型数组。直接赋值会将字符串存储在串池中,复用相同的字符串以节省内存。String 类提供了丰富的方法,如比较(equals() 和 compareTo())、查找(charAt() 和 indexOf())、转换(valueOf() 和 format())、拆分(split())和截取(substring())。此外,还介绍了 StringBuilder 和 StringJoiner 类,前者用于高效拼接字符串,后者用于按指定格式拼接字符串
19 1
Java——String类详解
|
15天前
|
安全 Java
Java StringBuffer 和 StringBuilder 类详解
在 Java 中,`StringBuffer` 和 `StringBuilder` 用于操作可变字符串,支持拼接、插入、删除等功能。两者的主要区别在于线程安全性和性能:`StringBuffer` 线程安全但较慢,适用于多线程环境;`StringBuilder` 非线程安全但更快,适合单线程环境。选择合适的类取决于具体的应用场景和性能需求。通常,在不需要线程安全的情况下,推荐使用 `StringBuilder` 以获得更好的性能。
|
15天前
|
Java 索引
Java String 类详解
Java 中的 `String` 类用于表示不可变的字符序列,是 Java 标准库 `java.lang` 包的一部分。字符串对象一旦创建,其内容不可更改,修改会生成新对象。
|
2月前
|
Java API 索引
【Java基础面试二十四】、String类有哪些方法?
这篇文章列举了Java中String类的常用方法,如`charAt()`、`substring()`、`split()`、`trim()`、`indexOf()`、`lastIndexOf()`、`startsWith()`、`endsWith()`、`toUpperCase()`、`toLowerCase()`、`replaceFirst()`和`replaceAll()`,并建议面试时展示对这些方法的熟悉度,同时深入理解部分方法的源码实现。
【Java基础面试二十四】、String类有哪些方法?
|
9天前
|
Java 索引
java基础扫盲-String类常用的方法
java基础扫盲-String类常用的方法
|
2月前
|
存储 SQL Java
Java 系类之 Java StringBuffer类详解
这篇文章详细介绍了Java中的StringBuffer类的使用,包括其构造方法、追加字符串、替换字符、反转字符串和删除字符串的方法,并提供了相应的示例代码。