Java--String类

news2024/9/20 20:32:00

 前言:


        在之前的学习中,学习了和了解了一些类的基本使用,例如object类等等,但是我们用String这个引用或者说这个类其实我们已经用了好久,只不过没有具体分析过!

        对于String类,它可以引用一个字符串,在C语言中没有一个类型是字符串类型。

接下来就来探究一下String类带给我们的一些方法。

常用方法:

1、构造方法:

        字符串的构造方法常见的有三种:

public class Test1 {
    public static void main(String[] args) {
        //方式一:
        String str = "abcd";
        //方式二:
        String str1 = new String("abcd");
        //方式三:
        char[] arr = {'a','b','c','d'};
        String str2 = new String(arr);
    }
}

由于String是引用类型,自己本身不存储数据,在String类中实例变量如下:

      String s1 = new String("hello");
        String s2 = new String("world");
        String s3 = s1;

如上这段代码是s1和s3是引用同一个对象的,画图解释:

注意:

        在Java中用" "引起来的也是String类型!!

字符串的比较:

        字符串的比较有四种情况:

1.比较String类型是否引用同一个对象:

        也就是用"=="比较两个引用的地址是否相同:

        

    public static void main(String[] args) {
        //对于基本变量“==”是比较两个值是否相等
        int a = 10;
        int b = 20;
        int c = 10;
        System.out.println(a == b);//fasle
        System.out.println(a == c);//true

        //对于String引用类型,比较地址
        String s1 = new String("abcd");
        String s2 = new String("abcd");
        String s3 = s1;
        System.out.println(s1 == s2);//false
        System.out.println(s1 == s3);//true
        System.out.println(s2 == s3);//false
    }

我们从结果也能看出!

但是!!!,这时候有一个问题:我用直接引用的方式,也就是不new直接引用一个字符串结果是否还是一样的呢?

    public static void main(String[] args) {
        String s1 ="abcd";
        String s2 = "abcd";
        String s3 = s1;
        System.out.println(s1 == s2);
        System.out.println(s1 == s3);
        System.out.println(s2 == s3);
    }

结果是:

三个true,难道说此时没有在比较地址?还是说没有在堆区开辟新的空间?
要谈就这个问题和"常量池"有关,放在后边的讲解中!
 

 2.equals方法按照字典序比较两个字符串

        也就是比较两个字符串中的每一个字符是不是都是一样的,如果一样就返回true,如果不一样就返回false!

        String类中的该方法时继承Object类中的equals方法,如果我们想要有自己的equals方法也可以重写。

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

此时可以看出结果,equals方法可以比较两个字符串里面的字符是不是一样的。

我们可以拿到equals的源码:

 public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

这个源码是Object类中的方法,被继承之后可以使用,这个源码的特点:

        1、当两个引用类型引用同一个对性的时候,也就是地址相同时,直接返回true

        2、检查两个引用的类型是否一样,如果不一样直接返回false。

        3. this和 anObject 两个字符串的长度是否相同,是继续比较,否则返回 false

        4、将字符串放入字符数组中,逐一比较每个字符的Ascall值是否一样。

3.compareTo方法 按照字典序比较

        这个方法比起equals方法更加精细化二了,equals方法只能告诉你两个字符串相不相等,

但是compareTo方法能够告诉你如果不相等那个字符串大。

        

    public static void main(String[] args) {
        String s1 = new String("abcdef");
        String s2 = new String("abc");
        String s3 = new String("efg");
        String s4 = new String("abcdef");
        System.out.println(s1.compareTo(s2));
        System.out.println(s1.compareTo(s3));
        System.out.println(s1.compareTo(s4));
    }

注意:     

1. 先按照字典次序大小比较,如果出现不等的字符,直接返回这两个字符的大小差值
2. 如果前 k 个字符相等 (k 为两个字符长度最小值 ) ,返回值两个字符串长度差值

源码如下:

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;
    }

 4、compareToIgnoreCase方法:

        与compareTo方式相同,但是忽略大小写比较。

    public static void main(String[] args) {
        String s1 = new String("abcdef");
        String s2 = new String("abc");
        String s3 = new String("efg");
        String s4 = new String("AbcdEf");
        System.out.println(s1.compareToIgnoreCase(s2));
        System.out.println(s1.compareToIgnoreCase(s3));
        System.out.println(s1.compareToIgnoreCase(s4));
    }

结果是:

发现s1和s4在大小写上有区别,但是该方法可以忽略大小写,直接比较!

字符串的查找:

        返回index位置上字符:

        也就是找到对应位置上的字符:

    public static void main(String[] args) {
        String s = "abcdefghhigkl";
        System.out.println(s.charAt(1));
        System.out.println(s.charAt(3));
        System.out.println(s.charAt(20));
    }

注意事项:        

如果index为负数或者越界,抛出IndexOutOfBoundsException异常

 返回字符第一次出现的位置:

        

    public static void main(String[] args) {
        String s = "abcdefghhigkl";
        System.out.println(s.indexOf('e'));
        System.out.println(s.indexOf('c'));
        System.out.println(s.indexOf('z'));
    }

 

注意事项:

       1. 如果index在字符串中没有则返回-1。

        2.参数index需要传字符,内部是用整形接收字符的ASCALL码值。

返回从指定位置开始第一次对应字符出现的位置:

    public static void main(String[] args) {
        String s = "abcdefghhigkl";
        System.out.println(s.indexOf('a',0));
        System.out.println(s.indexOf('a',2));
        System.out.println(s.indexOf('l',99));
    }

 返回指定字符串的位置:

        该方法可以返回指定字符串第一次出现的位置:

    public static void main(String[] args) {
        String s = "abcdefghhigkl";
        System.out.println(s.indexOf("igk"));
        System.out.println(s.indexOf("l"));
        System.out.println(s.indexOf("abcd"));
    }

如果没有就返回-1。

从后往前找对应字符串,返回对应位置:

    public static void main(String[] args) {
        String s = "abcdefghhigkl";
        System.out.println(s.lastIndexOf('d'));
        System.out.println(s.lastIndexOf('l'));
    }

其效果和indexOf一样的。

当然它同样也有一些重载的方法,这里就不一一列举了!!

转化:

    数值转字符串:

class Student{
    int age;
    String name;
    public Student(int age,String name){
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}
public class Test1 {
    public static void main(String[] args) {
        String s1 = String.valueOf(1234);
        String s2 = String.valueOf(12.34);
        String s3 = String.valueOf(true);
        String s4 = String.valueOf(new Student(13,"xiaoming"));
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
        System.out.println(s4);
    }

 字符串转数值:
        

    public static void main(String[] args) {
        String s1 = new String("12345");
        String s2 = new String("123.45");
        int a = Integer.parseInt(s1);
        double b = Double.parseDouble(s2);
        System.out.println(a);
        System.out.println(b);
    }

大小写转换:
 

    public static void main(String[] args) {
        String s1 = "abcde";
        String s2 = "HAHAHA";
        String s3 = "abcDEF";
        System.out.println(s1.toUpperCase());//小写转大写
        System.out.println(s2.toLowerCase());//大写转小写
        System.out.println(s3.toUpperCase());//小写转大写
        System.out.println(s3.toLowerCase());//大写转小写
    }

字符串转数组:

    public static void main(String[] args) {
        String s = "hello";
// 字符串转数组
        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 = "helloworld!";
        System.out.println(s.replaceAll("l", "_"));
        System.out.println(s.replaceFirst("l", "_"));
        System.out.println(s.replaceAll("hel","_"));
    }

注意:

        如果字符串中没有对应要替换的对象就返回原来的字符串!

字符串拆分:

String[] split(String regex)    将字符串全部拆分

可以将一个完整的字符串按照指定的分隔符划分为若干个子字符串。

    public static void main(String[] args) {
        String s = "abc def ghi";
        String[] s1 = s.split(" ");
        for (String s2:s1) {
            System.out.println(s2);
        }
    }

 

String[] split(String regex, int limit)   将字符串以指定的格式,拆分为limit
    public static void main(String[] args) {
        String s = "abc def ghi";
        String[] s1 = s.split(" ",2);
        for (String s2:s1) {
            System.out.println(s2);
        }
    }

 

特殊:

        拆分如下字符串:

    public static void main(String[] args) {
        String s = "192.182.1.13";
        String[] s1 = s.split(".");
        for (String x:s1) {
            System.out.println(x);
        }
    }

打印结果却不对劲。

注意:

1. 字符"." , "|" , "*" , "+" 都得加上转义字符,前面加上 "\\" .
2. 而如果是 "\" ,那么就得写成 "\\\\" .
3. 如果一个字符串中有多个分隔符,可以用"|"作为连字符.

 可以这样写:

    public static void main(String[] args) {
        String s = "192.182.1.13";
        String[] s1 = s.split("//.");
        for (String x:s1) {
            System.out.println(x);
        }
    }

多次拆分:
 

String str = "name=zhangsan&age=18" ;
String[] result = str.split("&") ;
for (int i = 0; i < result.length; i++) {
String[] temp = result[i].split("=") ;
System.out.println(temp[0]+" = "+temp[1]);
}

字符串截取:

String substring(int beginIndex)    从指定索引截取到结尾
String substring(int beginIndex, int endIndex)     截取部分内容

 

    public static void main(String[] args) {
        String s = "helloworld!!";
        System.out.println(s.substring(3));
        System.out.println(s.substring(3,8));
    }

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2140493.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

VTD激光雷达(1)——01_OptiX_RayTracing-笔记

文章目录 前言一、文档介绍1、 总结 前言 不想学习怎么办 感谢VTD官方视频指导 一、文档介绍 1、 1 2 站在光的角度上考虑问题&#xff0c;如果用光源发出的&#xff0c;好多没到传感器上&#xff0c;这样会导致计算量很大&#xff0c;我们用传感器的trace 3 4 5 6 7 8 …

如何在 Vue 3 + Element Plus 项目中实现动态设置主题色以及深色模式切换

&#x1f525; 个人主页&#xff1a;空白诗 文章目录 一、引言二、项目依赖和环境配置1. VueUse2. use-element-plus-theme3. 安装依赖 三、实现深色模式切换1. 设置深色模式状态2. 模板中的深色模式切换按钮3. 深色模式的效果展示 四、动态切换主题色五、总结 一、引言 在现代…

平安养老险阜阳中心支公司开展金融教育宣传专项活动

为全面深入开展“金融教育宣传月”的各项工作&#xff0c;不断完善金融惠民利民举措&#xff0c;提升金融服务质效&#xff0c;帮助基层群众增强维权意识、防非反诈的自我保护能力。近日&#xff0c;平安养老保险股份有限公司&#xff08;以下“平安养老险”&#xff09;阜阳中…

神经网络_使用tensorflow对fashion mnist衣服数据集分类

from tensorflow import keras import matplotlib.pyplot as plt1.数据预处理 1.1 下载数据集 fashion_mnist keras.datasets.fashion_mnist #下载 fashion mnist数据集 (train_images, train_labels),(test_images, test_labels) fashion_mnist.load_data()print("t…

食品包装识别系统源码分享

食品包装识别检测系统源码分享 [一条龙教学YOLOV8标注好的数据集一键训练_70全套改进创新点发刊_Web前端展示] 1.研究背景与意义 项目参考AAAI Association for the Advancement of Artificial Intelligence 项目来源AACV Association for the Advancement of Computer Vis…

IDEA复制代码到MD笔记格式还手动调,赶紧试试这个功能,一步到位

你是否曾经有过这种复制代码到笔记代码块的经历&#xff0c;选中后代码左侧有一些空格 然后粘到Markdown笔记里除第一行外&#xff0c;其他几行都要手动向前缩进&#xff0c;真是逼死强迫症啊 但是&#xff0c;其实idea工具中有一个“列选择模式”的功能&#xff0c;我们可以…

51单片机-LCD1602(液晶显示屏)- 写驱动

时间永远是检验真理唯一标准&#xff01;Whappy&#xff01; 主要简单写出几个驱动 初始化、显示字符、显示字符串、显示整形数据、有符号数据、十六进制、二进制&#xff01; void LCD_Init(); void LCD_ShowChar(unsigned char Line,unsigned char Column,char Char); vo…

【网络安全的神秘世界】csrf客户端请求伪造

&#x1f31d;博客主页&#xff1a;泥菩萨 &#x1f496;专栏&#xff1a;Linux探索之旅 | 网络安全的神秘世界 | 专接本 | 每天学会一个渗透测试工具 一、概述 跨站请求伪造&#xff0c;是一种挟持用户在当前已登陆的web应用程序上执行非本意操作的攻击方法&#xff0c;允许攻…

Comsol 利用多孔材料填充复合吸声器,拓宽低频完美吸声

参考文献&#xff1a;Cheng B , Gao N , Huang Y ,et al.Broadening perfect sound absorption by composite absorber filled with porous material at low frequency:[J].Journal of Vibration and Control, 2022, 28(3-4):410-424.DOI:10.1177/1077546320980214. 为了提高低…

端侧大模型系列 | 斯坦福手机端侧Agent大模型,为Android API而生!

0. 引言 峰峦或再有飞来&#xff0c;坐山门老等。泉水已渐生暖意&#xff0c;放笑脸相迎 小伙伴们好&#xff0c;我是微信公众号《小窗幽记机器学习》的小编&#xff1a;卖铁观音的小男孩。今天这篇小作文主要介绍端侧大模型中的函数调用&#xff0c;即常说的Function calling…

即插即用!高德西交的PriorDrive:统一的矢量先验地图编码,辅助无图自动驾驶

Driving with Prior Maps: Unified Vector Prior Encoding for Autonomous Vehicle Mapping 论文主页&#xff1a;https://misstl.github.io/PriorDrive.github.io/ 论文链接&#xff1a;https://arxiv.org/pdf/2409.05352 代码链接&#xff1a;https://github.com/missTL/Pr…

【数据结构】排序算法---直接插入排序

文章目录 1. 定义2. 算法步骤3. 动图演示4. 性质5. 算法分析6. 代码实现C语言PythonJavaCGo 7. 折半插入排序代码实现——C 结语 1. 定义 直接插入排序是一种简单直观的排序算法。它的工作原理为将待排列元素划分为「已排序」和「未排序」两部分&#xff0c;每次从「未排序的」…

PHP Swoole实现简易聊天室,附加小程序端连接websocket简易代码

目录 用到的工具&#xff1a; PHP Swoole拓展 | PHP Redis拓展 | Redis 7 一、安装上述必要工具&#xff08;下面是以宝塔面板中操作为例&#xff09; 给PHP安装Swoole和Redis拓展&#xff1a; 安装Redis软件 二、创建websocket服务器文件"wss_server.php" 具…

node.js+Koa框架+MySQL实现注册登录

完整视频展示&#xff1a;https://item.taobao.com/item.htm?ftt&id831092436619&spma21dvs.23580594.0.0.52de2c1bg9gTfM 效果展示&#xff1a; 一、项目介绍 本项目是基于node.jsKoamysql的注册登录的项目,主要是给才学习node.js和Koa框架的萌新才写的。 二、项目…

java数据结构----图

图的存储结构: 代码实现 public class Graph {// 标记顶点数目private int V;// 标记边数目private int E;// 邻接表private Queue<Integer>[] adj;public Graph(int v) {V v;this.E 0;this.adj new Queue[v];for (int i 0; i < adj.length; i) {adj[i] new Queu…

C++的类与对象中(主讲默认成员函数)

目录 1.类的默认成员函数 2.构造函数 1.全缺省构造函数 2.第7点中的对自定义类型的成员变量构造&#xff08;调用编译器自动生成的默认构造函数&#xff09; 3.析构函数 4.拷贝构造函数 5.运算符重载 1.概念 2.赋值运算符重载 6.const成员函数 1.类的默认成员函数 默…

微服务——网关路由(Spring Cloud Gateway)

网关路由 1.什么是网关 网关又称网间连接器、协议转换器&#xff0c;是在网络层以上实现网络互连的复杂设备&#xff0c;主要用于两个高层协议不同的网络之间的互连。网关就是网络的关口。数据在网络间传输&#xff0c;从一个网络传输到另一网络时就需要经过网关来做数据的路由…

【深度智能】:迈向高级时代的人工智能全景指南

​ ​ 前几天偶然发现了一个超棒的人工智能学习网站&#xff0c;内容通俗易懂&#xff0c;讲解风趣幽默&#xff0c;简直让人欲罢不能。忍不住分享给大家&#xff0c;人工智能立刻跳转&#xff0c;开启你的AI学习之旅吧&#xff01; 第一阶段&#xff1a;基础知识 1. 计算机科…

人脸防伪检测系统源码分享

人脸防伪检测检测系统源码分享 [一条龙教学YOLOV8标注好的数据集一键训练_70全套改进创新点发刊_Web前端展示] 1.研究背景与意义 项目参考AAAI Association for the Advancement of Artificial Intelligence 项目来源AACV Association for the Advancement of Computer Vis…

【Python基础】Python 装饰器(优雅的代码增强工具)

本文收录于 《Python编程入门》专栏&#xff0c;从零基础开始&#xff0c;分享一些Python编程基础知识&#xff0c;欢迎关注&#xff0c;谢谢&#xff01; 文章目录 一、前言二、装饰器基础三、语法糖 四、带参数的装饰器五、多层装饰器六、总结 一、前言 在Python编程的世界里…