【Java】认识String类

文章目录

  • 一、String类的重要性
  • 二、String类中的常用方法
    • 1.字符串构造
    • 2.String对象的比较
    • 3.字符串查找
    • 4.转换
    • 5.字符串替换
    • 6.字符串拆分
    • 7.字符串截取
    • 8.其他操作方法
    • 9.字符串的不可变性
    • 10.字符串修改
  • 三、StringBuilder和StringBuffer


一、String类的重要性

在C语言中已经涉及到字符串了,但是在C语言中要表示字符串只能使用字符数组或者字符指针,可以使用标准库提供的字符串系列函数完成大部分操作,但是这种将数据和操作数据方法分离开的方式不符合面相对象的思想,而字符串应用又非常广泛,因此Java语言专门提供了String类

二、String类中的常用方法

1.字符串构造

String类提供的构造方式非常多,常用的有以下三种:

public class Test {
    public static void main(String[] args) {
        String s = "hello";
        System.out.println(s);
        String s1 = new String("hello");
        System.out.println(s1);
        char[] s3 = {'h','e','l','l','o'};
        System.out.println(s3);
    }
}

在这里插入图片描述
注意:
1.String类是引用类型,内部并不存储字符串本身
2.在Java中""引起来的也是String类型对象

2.String对象的比较

Java中提供了四种比较方式:
1.==比较是否引用同一对象

public class Test {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        int c = 10;
        System.out.println(a==b);
        System.out.println(a==c);
        System.out.println("********");
        String s = new String("hello");
        String s1 = new String("hello");
        String s2 = new String("word");
        String s3 = s;
        System.out.println(s==s1);
        System.out.println(s1==s2);
        System.out.println(s==s3);
    }
}

在这里插入图片描述
注意: 对于内置类型,== 比较的是变量中的值;对于引用类型==比较的是引用中的地址

2.boolean equals(Object anObject) 方法:按照字典序比较
字典序:字符大小的顺序
String类重写了父类Object中equals方法,Object中equals默认按照==比较,String重写equals方法后,按照如下规则进行比较

public class Test {
    public static void main(String[] args) {
        String s = new String("hello");
        String s1 = new String("hello");
        String s2 = new String("Hello");
        // equals比较:String对象中的逐个字符
        // s与s2引用的不是同一个对象,而且两个对象中内容也不同,因此输出false
         // s与s1引用的不是同一个对象,但是两个对象中放置的内容相同,因此输出true
        System.out.println(s.equals(s2));
        System.out.println(s.equals(s1));
    }
}

在这里插入图片描述
3.int compareTo(String s) 方法: 按照字典序进行比较
与equals不同的是,equals返回的是boolean类型,而compareTo返回的是int类型。具体比较方式:
1.先按照字典次序大小比较,如果出现不等的字符,直接返回这两个字符的大小差值
2.如果前k个字符相等(k为两个字符长度最小值),返回值两个字符串长度差值

public class Test {
    public static void main(String[] args) {
        String s = new String("abc");
        String s1 = new String("ac");
        String s2 = new String("abc");
        String s3 = new String("abcde");
        System.out.println(s.compareTo(s1));//不同输出字符的差值为-1
        System.out.println(s.compareTo(s2));//输出字符相同为0
        System.out.println(s.compareTo(s3));//前几个字符相同,输出长度差值为-2
    }
}    

在这里插入图片描述
4. int compareToIgnoreCase(String str) 方法:与compareTo方式相同,但是忽略大小写比较

public class Test {
    public static void main(String[] args) {
        String s = new String("abc");
        String s1 = new String("ac");
        String s2 = new String("ABc");
        String s3 = new String("abcde");
        System.out.println(s.compareToIgnoreCase(s1));//不同输出字符的差值为-1
        System.out.println(s.compareToIgnoreCase(s2));//输出字符相同为0
        System.out.println(s.compareToIgnoreCase(s3));//前几个字符相同,输出长度差值为-2
    }
}    

在这里插入图片描述

3.字符串查找

字符串查找也是字符串中非常常见的操作,String类提供的常用查找的方法:

方法功能
char charAt(int index)返回index位置上字符,如果index为负数或者越界,抛出IndexOutOfBoundsException异常
int indexOf(int ch)返回ch第一次出现的位置,没有返回-1
int indexOf(int ch, int fromIndex)从fromIndex位置开始找ch第一次出现的位置,没有返回-1
int indexOf(String str)返回str第一次出现的位置,没有返回-1
int indexOf(String str, int fromIndex)从fromIndex位置开始找str第一次出现的位置,没有返回-1
int lastIndexOf(int ch)从后往前找,返回ch第一次出现的位置,没有返回-1
int lastIndexOf(int ch, int fromIndex)从fromIndex位置开始找,从后往前找ch第一次出现的位置,没有返回-1
:int lastIndexOf(String str)从后往前找,返回str第一次出现的位置,没有返回-1:
int lastIndexOf(String str, int fromIndex)从fromIndex位置开始找,从后往前找str第一次出现的位置,没有返回-1
public class Test {
    public static void main(String[] args) {
        String s = "aaabbbcccaaabbbccc";
        System.out.println(s.charAt(3)); 
        System.out.println(s.indexOf('c'));
        System.out.println(s.indexOf('c', 10));
        System.out.println(s.indexOf("bbb"));
        System.out.println(s.indexOf("bbb", 10));
        System.out.println(s.lastIndexOf('c'));
        System.out.println(s.lastIndexOf('c', 10));
        System.out.println(s.lastIndexOf("bbb"));
        System.out.println(s.lastIndexOf("bbb", 10));
    }
}

在这里插入图片描述

4.转换

1.数值和字符串转换化

public class Test {
    public static void main(String[] args) {
        String s1 = String.valueOf(1234);
        String s2 = String.valueOf(12.34);
        String s3 = String.valueOf(true);
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
        System.out.println("=================================");
        // 字符串转数字
        // 注意:Integer、Double等是Java中的包装类型
        int data1 = Integer.parseInt("1234");
        double data2 = Double.parseDouble("12.34");
        System.out.println(data1);
        System.out.println(data2);
    }
}

在这里插入图片描述
2.大小写转换

public class Test {
    public static void main(String[] args) {
        String s = "hello";
        String s1 = "HELLO";
        System.out.println(s.toUpperCase());//小写转大写
        System.out.println(s1.toLowerCase());//大写转小写
    }
}    

在这里插入图片描述
这两个函数只转换字母
3.字符串转数组

public class Test {
    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);
    }
}

在这里插入图片描述
4.格式化

public class Test {
    public static void main(String[] args) {
        String s = String.format("%d-%d-%d", 2019, 9,14);
        System.out.println(s);
    }
}

在这里插入图片描述

5.字符串替换

使用一个指定的新的字符串替换掉已有的字符串数据,可用的方法如下:

方法功能
String replaceAll(String regex, String replacement)替换所有的指定内容
String replaceFirst(String regex, String replacement)替换收个内容
public class Test {
    public static void main(String[] args) {
        String s = "hellohello";
        System.out.println(s.replaceAll("l", "z"));
        System.out.println(s.replaceFirst("l", "z"));
    }
}    

在这里插入图片描述
注意事项: 由于字符串是不可变对象, 替换不修改当前字符串, 而是产生一个新的字符串

6.字符串拆分

可以将一个完整的字符串按照指定的分隔符划分为若干个子字符串
方法如下:

方法功能
String[] split(String regex)将字符串全部拆分
String[] split(String regex, int limit)将字符串以指定的格式,拆分为limit组
public class Test {
    public static void main(String[] args) {
        String str = "hello word is you";
        String[] s = str.split(" ");//按照空格拆分
        for (int i = 0; i < s.length; i++) {
            System.out.println(s[i]);
        }
    }
}

在这里插入图片描述

public class Test {
    public static void main(String[] args) {
        String str = "hello word is you";
        String[] s = str.split(" ",2);//按照空格拆分成两份
        for (int i = 0; i < s.length; i++) {
            System.out.println(s[i]);
        }
    }
}    

在这里插入图片描述
拆分是特别常用的操作. 一定要重点掌握. 另外有些特殊字符作为分割符可能无法正确切分, 需要加上转义
注意事项:
1.字符"|“,”*“,”+“都得加上转义字符,前面加上 “\”
2.而如果是 “” ,那么就得写成 “\\”
3.如果一个字符串中有多个分隔符,可以用”|"作为连字符
多次拆分:

public class Test {
    public static void main(String[] args) {
        String str = "name=zhagnsan&age=10";
        String[] s = str.split("&");
        for (String ss:s) {
            String[] ret = ss.split("=");
            for (String sss:ret) {
                System.out.println(sss);
            }
        }
    }
}

在这里插入图片描述

7.字符串截取

从一个完整的字符串之中截取出部分内容
方法如下:

方法功能
String substring(int beginIndex)从指定索引截取到结尾
String substring(int beginIndex, int endIndex)截取部分内容
public class Test {
    public static void main(String[] args) {
        String str = "helloword";
        System.out.println(str.substring(5));
        System.out.println(str.substring(0, 5));
    }
}    

在这里插入图片描述
注意事项
1.索引从0开始
2.注意前闭后开区间的写法,substring(0,5)表示包含0下标的字符,不包含5下标的字符

8.其他操作方法

方法功能
String trim()去掉字符串中的左右空格,保留中间空格
String toUpperCase()字符串转大写
String toLowerCase()字符串转小写
public class Test {
    public static void main(String[] args) {
        String str = " hello word ";
        System.out.println(str.trim());
    }
}    

在这里插入图片描述
trim 会去掉字符串开头和结尾的空白字符(空格, 换行, 制表符等)

9.字符串的不可变性

String是一种不可变对象. 字符串中的内容是不可改变。字符串不可被修改,是因为:
1.String类在设计时就是不可改变的,String类实现描述中已经说明了
在这里插入图片描述
String类中的字符实际保存在内部维护的value字符数组中,从上图中可以看出:
1.String类被final修饰,表示该类不能被继承
2.value被final修饰,表明value自身的值不能改变,即不能引用其它字符数组,但是其引用空间中的内容可以修改
2. 所有涉及到可能修改字符串内容的操作都是创建一个新对象,改变的是新对象
字符串不可变是因为其内部保存字符的数组被final修饰了,因此不能改变。
这种说法是错误的,不是因为String类自身,或者其内部value被final修饰而不能被修改。
final修饰类表明该类不想被继承,final修饰引用类型表明该引用变量不能引用其他对象,但是其引用对象中的内容是可以修改的

10.字符串修改

注意: 尽量避免直接对String类型对象进行修改,因为String类是不能修改的,所有的修改都会创建新对象,效率非常低下

三、StringBuilder和StringBuffer

由于String的不可更改特性,为了方便字符串的修改,Java中又提供StringBuilder和StringBuffer类。这两个类大部分功能是相同的

方法功能
StringBuff append(String str)在尾部追加,相当于String的+=,可以追加:boolean、char、char[]、double、float、int、long、Object、String、StringBuff的变量
char charAt(int index)获取index位置的字符
int length()获取字符串的长度
int capacity()获取底层保存字符串空间总的大小
void ensureCapacity(int mininmumCapacity)扩容
void setCharAt(int index,char ch)将index位置的字符设置为ch
int indexOf(String str)返回str第一次出现的位置
int indexOf(String str, int fromIndex)从fromIndex位置开始查找str第一次出现的位置
int lastIndexOf(String str)返回最后一次出现str的位置
int lastIndexOf(String str,int fromIndex)从fromIndex位置开始找str最后一次出现的位置
StringBuff insert(int offset, String str)在offset位置插入:八种基类类型 & String类型 & Object类型数据
StringBuffer deleteCharAt(int index)删除index位置字符
StringBuffer delete(int start, int end)删除[start, end)区间内的字符
StringBuffer replace(int start, int end, String str)将[start, end)位置的字符替换为str
String substring(int start)从start开始一直到末尾的字符以String的方式返回
String substring(int start,int end)将[start, end)范围内的字符以String的方式返回
StringBuffer reverse()反转字符串
String toString()将所有字符按照String的方式返回

String和StringBuilder最大的区别在于String的内容无法修改,而StringBuilder的内容可以修改。频繁修改字符串的情况考虑使用StringBuilder
注意: String和StringBuilder类不能直接转换。如果要想互相转换,可以采用如下原则:
1.String变为StringBuilder: 利用StringBuilder的构造方法或append()方法
2.StringBuilder变为String: 调用toString()方法

String、StringBuffer、StringBuilder的区别
1.String的内容不可修改,StringBuffer与StringBuilder的内容可以修改.
2.StringBuffer与StringBuilder大部分功能是相似的
3.StringBuffer采用同步处理,属于线程安全操作;而StringBuilder未采用同步处理,属于线程不安全操作

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

微型计算机原理MOOC题

一、8254 1.掉坑了&#xff0c;AL传到端口不意味着一定传到的是低位&#xff0c;要看控制字D5和D4&#xff0c;10是只写高位&#xff0c;所以是0A00.。。 2. 3. 4.待解决&#xff1a;

leetCode 2925. 在树上执行操作以后得到的最大分数 + 正则难反 + 树形 DP

2925. 在树上执行操作以后得到的最大分数 - 力扣&#xff08;LeetCode&#xff09; 有一棵 n 个节点的无向树&#xff0c;节点编号为 0 到 n - 1 &#xff0c;根节点编号为 0 。给你一个长度为 n - 1 的二维整数数组 edges 表示这棵树&#xff0c;其中 edges[i] [ai, bi] 表示…

【从零开始实现意图识别】中文对话意图识别详解

前言 意图识别&#xff08;Intent Recognition&#xff09;是自然语言处理&#xff08;NLP&#xff09;中的一个重要任务&#xff0c;它旨在确定用户输入的语句中所表达的意图或目的。简单来说&#xff0c;意图识别就是对用户的话语进行语义理解&#xff0c;以便更好地回答用户…

JS数组常用的20种方法详解(每一个方法都有例子,超全面,超好理解的教程,干货满满)

目录 1.会改变原数组的方法&#xff08;7种&#xff09; 1.push() 2.pop() 3.unshift() 4.shift() 5.reverse() 6.sort() 7.splice() 2.不改变原数组的方法&#xff08;13种&#xff0c;返回的新数组是从原数组浅拷贝来的&#xff09; 1.concat() 2.join() 3.slice…

九、ffmpeg命令转封装

开了几天小差&#xff0c;今天继续学习ffmpeg。 准备测试使用的视频&#xff0c;并查看其信息 # 查看视频信息。使用Mediainfo也可以 ffprobe test.mp4 视频格式的信息如下。 保持编码格式&#xff1a;ffmpeg -i test.mp4 -vcodec copy -acodec copy test_copy.tsffmpeg -i…

2015年2月4日 Go生态洞察:Go语言中的包命名艺术

&#x1f337;&#x1f341; 博主猫头虎&#xff08;&#x1f405;&#x1f43e;&#xff09;带您 Go to New World✨&#x1f341; &#x1f984; 博客首页——&#x1f405;&#x1f43e;猫头虎的博客&#x1f390; &#x1f433; 《面试题大全专栏》 &#x1f995; 文章图文…

王道p150 20.将给定的表达式树转化为等价的中缀表达式(通过括号反应操作符的计算次序)

本题代码如下 void btreetoexp(tree t, char deep) {if (t NULL)return;else if (t->lchild NULL && t->rchild NULL)printf("%c", t->data);//输出操作数&#xff0c;不加括号else {if (deep > 1)printf("(");btreetoexp(t->l…

231123 刷题日报-动态规划

今天主要看了DP&#xff0c;前几天频繁遇到DP打击有点大。。 1. 0-1背包问题 要点&#xff1a; a. 三部曲&#xff1a; 1. 状态和选择 状态&#xff1a;物品序号、背包容量 选择&#xff1a;放、不放 2. dp数组定义、base case dp[i][w] 对于前i个物品&#xff0c;当前背包…

UNETR:用于三维医学图像分割的Transformer

论文链接&#xff1a;https://arxiv.org/abs/2103.10504 代码链接&#xff1a; https://monai.io/research/unetr 机构&#xff1a;Vanderbilt University, NVIDIA 最近琢磨不出来怎么把3d体数据和文本在cnn中融合&#xff0c;因为确实存在在2d里面用的transformer用在3d里面…

leetcode刷题之用栈实现队列(C语言版)

leetcode刷题之用栈实现队列&#xff08;C语言版&#xff09; 一、题目描述二、题目要求三、题目解析Ⅰ、typedef structⅡ、MyQueue* myQueueCreateⅢ、void myQueuePush(MyQueue* obj, int x)Ⅳ、int myQueuePeek(MyQueue* obj)Ⅴ、int myQueuePop(MyQueue* obj)Ⅶ、bool myQ…

编译器核心技术概览

编译技术是一门庞大的学科&#xff0c;我们无法对其做完善的讲解。但不同用途的编译器或编译技术的难度可能相差很大&#xff0c;对知识的掌握要求也会相差很多。如果你要实现诸如 C、JavaScript 这类通用用途语言&#xff08;general purpose language&#xff09;&#xff0c…

[shader] 光照入门(未完结。。。

反射 漫反射&#xff1a;而当物体表面粗糙时&#xff0c;我们把物体表面看作无数不同方向的微小镜面&#xff0c;则这些镜面反射出的光方向均不相同&#xff0c;这就是漫反射。 高光反射&#xff1a;我们假定物体表面光滑&#xff0c;只有一个镜面&#xff0c;那么所有的光都…

微信小程序前端环境搭建

搭建微信小程序前端环境 申请小程序测试账号 访问路径 使用微信扫描二维码进行申请&#xff0c;申请成功之后&#xff0c;进入界面&#xff0c;获取小程序ID(AppID)和秘钥(AppSecret) 安装微信web开发者工具 访问路径 选择稳定开发的版本 需要在小程序的设置中将默认关闭…

深入理解JVM 类加载机制

深入理解JVM 类加载机制 虚拟机如何加载Class文件&#xff1f; Class文件中的信息进入到虚拟机后会发生什么变化&#xff1f; 类加载机制就是Java虚拟机把描述类的数据从Class文件加载到内存&#xff0c;并对数据进行校验、转换解析和初始化&#xff0c;最终形成可以被虚拟机…

AMEYA360:瑞萨面向高端工业传感器系统推出高精度模拟前端的32位RX MCU

全球半导体解决方案供应商瑞萨电子&#xff08;TSE&#xff1a;6723&#xff09;宣布面向高端工业传感器系统推出一款全新RX产品——RX23E-B&#xff0c;扩展32位微控制器&#xff08;MCU&#xff09;产品线。新产品作为广受欢迎的RX产品家族的一员&#xff0c;具有高精度模拟前…

3D火山图绘制教程

一边学习&#xff0c;一边总结&#xff0c;一边分享&#xff01; 本期教程内容 **注&#xff1a;**本教程详细内容 Volcano3D绘制3D火山图 一、前言 火山图是做差异分析中最常用到的图形&#xff0c;在前面的推文中&#xff0c;我们也推出了好几期火山图的绘制教程&#xff0…

如何通过宝塔面板搭建一个本地MySQL数据库服务并实现远程访问

宝塔安装MySQL数据库&#xff0c;并内网穿透实现公网远程访问 文章目录 宝塔安装MySQL数据库&#xff0c;并内网穿透实现公网远程访问前言1.Mysql服务安装2.创建数据库3.安装cpolar3.2 创建HTTP隧道 4.远程连接5.固定TCP地址5.1 保留一个固定的公网TCP端口地址5.2 配置固定公网…

Axios 通过a标签下载文件 跨域下载

<!-- a标签占位 --><a ref"down" ></a>getTest() {this.$axios.request({url: https://cnv13.55.la/download?file_key3695fa9461a0ae59cf3148581e4fe339&handle_typeexcel2pdf,method: get,responseType: blob, // 切记类型 blob}).then(re…

java:CommandLineRunner命令行操作

背景 CommandLineRunner是一个SpringBoot提供的接口&#xff0c;这个接口可以让我们在SpringBoot启动之后&#xff0c;执行一些特定的命令行操作。 实现CommandLineRunner接口后&#xff0c;SpringBoot在启动的时候会自动执行run方法。通常&#xff0c;我们可以在run方法中进…

TableStructureRec: 表格结构识别推理库来了

目录 引言lineless_table_rec: 无线表格识别库安装使用结果 wired_table_rec&#xff1a;有线表格识别库安装使用结果 写在最后 引言 TableStructureRec 仓库是用来对文档中表格做结构化识别的推理库&#xff0c;包括来自 PaddleOCR 的表格结构识别算法模型、来自阿里读光有线…
最新文章