【Java】详解String类中的各种方法

创建字符串

常见的创建字符串的三种方式:

// 方式一
String str = "hello world";
// 方式二
String str2 = new String("hello world");
// 方式三
char[] array = {'a', 'b', 'c'};
String str3 = new String(array);

"hello" 这样的字符串字面值常量, 类型也是 String.
String 也是引用类型. String str = "Hello"; 这样的代码内存布局如下:

 

 下面我来写一个代码:

String str1 = "hallo";
String str2 = str1;
str1 = "world";
Systrm.out.println(str2);

很多人是否会认为 str1 的值改变了因此 str2 的值也跟着改变了,事实上 str1 里面的值并非是改变了而是指向了一个新的字符串。所以 str2 里面的值还是 hallo 。

 此时该代码在内存中的布局是这样的:

 判断字符串相等

在整型中我们判断两个整形是否相等用的是一下的方法:

int x = 10;
int y = 10;
if(x == y){
 System.out.println(true);
}

但是在字符串中我们能否也用这个方法呢?

我们用代码试试:

我们乍一看好像是可以的,但是我们换一个方法试试呢?

答案是错误的!

注意: String 使用 == 比较并不是在比较字符串内容, 而是比较两个引用是否是指向同一个对象。

Java 中要想比较字符串的内容, 必须采用String类提供的equals方法。

字符、字节与字符串

字符与字符串

将字符数组转变为字符串

public class Test {
    public static void main(String[] args) {
        char[] array = {'a','b','c','d'};
        String str1 = new String(array);
        System.out.println(str1);
        String str2 = new String(array,0,2);
        System.out.println(str2);
    }
}

输出结果:

 在将字符数组转变为字符串时既可以将整个数组转变为字符串也可以指定范围。

字符串转变为字符数组

public class Test {
    public static void main(String[] args) {
        String str = "abcdef";
        char[] array = str.toCharArray();
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }
}

输出结果:

获取字符串指定位置的字符

public class Test {
    public static void main(String[] args) {
        String str = "abcdef";
        char ch = str.charAt(1);
        System.out.println(ch);
    }
}

字节与字符串

将字符串转变为字节数组

public class Test {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String str = "halloworld";
        byte[] array = str.getBytes();
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }
}

运行结果:

字符串常见操作

字符串比较

区分大小写的比较

public class Test {
    public static void main(String[] args) {
        String str1 = "abcd";
        String str2 = "abcd";
        if(str1.equals(str2)){
            System.out.println(true);
        }else{
            System.out.println(false);
        }
    }
}

 不区分大小写的比较

public class Test {
    public static void main(String[] args) {
        String str1 = "abcd";
        String str2 = "AbCd";
        if(str1.equalsIgnoreCase(str2)){
            System.out.println(true);
        }else{
            System.out.println(false);
        }
    }
}

比较两个字符串的大小

public class Test {
    public static void main(String[] args) {
        String str1 = "abcd";
        String str2 = "dsjkowjrd";
        System.out.println(str1.compareTo(str2));
        System.out.println(str1.compareToIgnoreCase(str2));
    }
}

字符串的查找

判断一个子字符串是否存在

public class Test {
    public static void main(String[] args) {
        String str1 = "halloworld";
        System.out.println(str1.contains("world"));
    }
}

查找指定字符串的位置

public class Test {
    public static void main(String[] args) {
        String str = "halloworld";
        System.out.println(str.indexOf("ow"));//从开始往后查找子字符串的位置
        System.out.println(str.indexOf("ow",3));//从指定位置开始往后查找子字符串的位置
        System.out.println(str.lastIndexOf("ow"));//从后往前查找子字符串的位置
        System.out.println(str.lastIndexOf("ow",7));//由指定位置从后往前查找子字符串的位置
    }
}

查找到了则返回子字符串的起始位置,没有查找到则返回 -1。

判断字符串是否以给定字符串开头

public class Test {
    public static void main(String[] args) {
        String str = "halloworld";
        System.out.println(str.startsWith("ha"));//从头开始判断字符串是否以该子字符串开头
        System.out.println(str.startsWith("ll",2));//从指定位置开始判断字符串是否以该子字符串开头
    }
}

判断字符串是否以给定字符串结尾

public class Test {
    public static void main(String[] args) {
        String str = "halloworld";
        System.out.println(str.endsWith("ld"));
    }
}

字符串替换

使用一个指定的新的字符串替换掉已有的字符串数据

public class Test {
    public static void main(String[] args) {
        String str = "halloworld";
        String str1 = str.replaceAll("l","ww");//替换所有的指定内容
        System.out.println(str1);
        String str2 = str.replaceFirst("l","ww");//替换第一个出现的指定内容
        System.out.println(str2);
    }
}

由于字符串是不可变对象, 替换不修改当前字符串, 而是产生一个新的字符串

字符串拆分

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

public class Test {
    public static void main(String[] args) {
        String str = "hallo world zhang san";
        String[] array = str.split(" ");//按照指定分隔符拆分成若干个子字符串
        for(String s : array){
            System.out.println(s);
        }
        String[] array1 = str.split(" ",2);//按照指定分隔符拆分成2个字符串
        for(String s : array1){
            System.out.println(s);
        }
    }
}

拆分是特别常用的操作. 一定要重点掌握. 另外有些特殊字符作为分割符可能无法正确切分, 需要加上转义。

例如拆分IP地址:

public class Test {
    public static void main(String[] args) {
        String str = "192.166.1.1";
        String[] array = str.split("\\.");
        for(String s : array){
            System.out.println(s);
        }
    }
}

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

字符串的截取

public class Test {
    public static void main(String[] args) {
        String str = "halloworld";
        String str1 = str.substring(5);//从指定位置截取到最后
        String str2 = str.substring(0,5);//截取一个范围的内容
        System.out.println(str1);
        System.out.println(str2);
    }
}

去除字符串左右空格保留中间空格

public class Test {
    public static void main(String[] args) {
        String str = "   hallo world   ";
        String str1 = str.trim();
        System.out.println(str1);
    }
}

字符串转大写

public class Test {
    public static void main(String[] args) {
        String str = "halloworld";
        String str1 = str.toUpperCase();
        System.out.println(str1);
    }
}

字符串转小写

public class Test {
    public static void main(String[] args) {
        String str = "HALLOworld";
        String str1 = str.toLowerCase();
        System.out.println(str1);
    }
}

字符串入池

public class Test {
    public static void main(String[] args) {
        String str = new String("halloworld").intern();
    }
}

字符串连接

public class Test {
    public static void main(String[] args) {
        String str = "hallo";
        String str1 = str.concat("world");
        System.out.println(str1);
    }
}

判断字符串是否为空

public class Test {
    public static void main(String[] args) {
        String str = "";
        System.out.println(str.isEmpty());
    }
}

空的意思是该字符串长度为0.

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

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

相关文章

昇思学习打卡-8-FCN图像语义分割

目录 FCN介绍FCN所用的技术训练数据的可视化模型训练模型推理FCN的优点和不足优点不足 FCN介绍 FCN主要用于图像分割领域&#xff0c;是一种端到端的分割方法&#xff0c;是深度学习应用在图像语义分割的开山之作。通过进行像素级的预测直接得出与原图大小相等的label map。因…

3-4 优化器和学习率

3-4 优化器和学习率 主目录点这里 优化器是机器学习和深度学习模型训练过程中用于调整模型参数的方法。它的主要目标是通过最小化损失函数来找到模型参数的最优值&#xff0c;从而提升模型的性能。 在深度学习中&#xff0c;优化器使用反向传播算法计算损失函数相对于模型参数…

C++ 函数高级——函数的占位参数

C中函数的形参列表里可以有占位参数&#xff0c;用来做占位&#xff0c;调用函数时必须填补改位置 语法&#xff1a; 返回值类型 函数名&#xff08;数据类型&#xff09;{ } 在现阶段函数的占位参数存在意义不大&#xff0c;但是后面的课程中会用到该技术 示例&#xff1a;…

TypeScript:5分钟上手创建一个简单的Web应用

一、练习TypeScript实例 1.1 在src目录里创建greeter.ts greeter.ts文件代码 // https://www.tslang.cn/docs/handbook/typescript-in-5-minutes.html // 格式化快捷键&#xff1a;https://blog.csdn.net/Dontla/article/details/130255699 function greeter(name: string) …

Windows电脑下载、安装VS Code的方法

本文介绍Visual Studio Code&#xff08;VS Code&#xff09;软件在Windows操作系统电脑中的下载、安装、运行方法。 Visual Studio Code&#xff08;简称VS Code&#xff09;是一款由微软开发的免费、开源的源代码编辑器&#xff0c;支持跨平台使用&#xff0c;可在Windows、m…

采煤机作业3D虚拟仿真教学线上展示增强应急培训效果

在化工行业的生产现场&#xff0c;安全永远是首要之务。为了加强从业人员的应急响应能力和危机管理能力&#xff0c;纷纷引入化工行业工艺VR模拟培训&#xff0c;让应急演练更加生动、高效。 化工行业工艺VR模拟培训软件基于真实的厂区环境&#xff0c;精确还原了各类事件场景和…

vue2 webpack使用optimization.splitChunks分包,实现按需引入,进行首屏加载优化

optimization.splitChunks的具体功能和配置信息可以去网上自行查阅。 这边简单讲一下他的使用场景、作用、如何使用&#xff1a; 1、没用使用splitChunks进行分包之前&#xff0c;所有模块都揉在一个文件里&#xff0c;那么当这个文件足够大、网速又一般的时候&#xff0c;首…

Transformer-LSTM预测 | Matlab实现Transformer-LSTM多变量时间序列预测

Transformer-LSTM预测 | Matlab实现Transformer-LSTM多变量时间序列预测 目录 Transformer-LSTM预测 | Matlab实现Transformer-LSTM多变量时间序列预测效果一览基本介绍程序设计参考资料 效果一览 基本介绍 1.Matlab实现Transformer-LSTM多变量时间序列预测&#xff0c;Transf…

玫瑰千层烤饼:味蕾的芬芳盛宴

在美食的缤纷世界里&#xff0c;有一种独特的存在&#xff0c;它融合了玫瑰的芬芳与烤饼的酥脆&#xff0c;那便是令人陶醉的甘肃美食玫瑰千层烤饼。食家巷玫瑰千层烤饼&#xff0c;宛如一件精心雕琢的艺术品。每一层薄如纸张的面皮&#xff0c;都承载着制作者的细腻与用心。层…

MySQL Binlog详解:提升数据库可靠性的核心技术

文章目录 1. 引言1.1 什么是MySQL Bin Log&#xff1f;1.2 Bin Log的作用和应用场景 2. Bin Log的基本概念2.1 Bin Log的工作原理2.2 Bin Log的三种格式 3. 配置与管理Bin Log3.1 启用Bin Log3.2 配置Bin Log参数3.3 管理Bin Log文件3.4 查看Bin Log内容3.5 使用mysqlbinlog工具…

vue3项目 前端blocked:mixed-content问题解决方案

一、问题分析 blocked:mixed-content其实浏览器不允许在https页面里嵌入http的请求&#xff0c;现在高版本的浏览器为了用户体验&#xff0c;都不会弹窗报错&#xff0c;只会在控制台上打印一条错误信息。一般出现这个问题就是在https协议里嵌入了http请求&#xff0c;解决方法…

多线程(进阶)

前言&#x1f440;~ 上一章我们介绍了线程池的一些基本概念&#xff0c;今天接着分享多线程的相关知识&#xff0c;这些属于是面试比较常见的&#xff0c;大部分都是文本内容 常见的锁策略 乐观锁 悲观锁 轻量锁 重量级锁 自旋锁 挂起等待锁 可重入锁和不可重入锁 互斥…

优化后Day53 动态规划part11

LC1143最长公共子序列 1.dp数组的含义&#xff1a;dp[i][j]表示以下标i结尾的text1子序列和以下标j结尾的text2子序列的最长公共子序列 2. 初始化&#xff1a;跟LC718一样&#xff0c;i结尾的需要初始化&#xff0c;i-1结尾不需要初始化 3. 递推公式 如果charAt(i)charAt(j)&…

C++ 函数高级——函数重载——注意事项

1.引用作为重载条件 2.函数重载碰到函数默认参数 示例&#xff1a; 运行结果&#xff1a;

【IMU】 确定性误差与IMU_TK标定原理

1、确定性误差 MEMS IMU确定性误差模型 K 为比例因子误差 误差来源:器件的输出往往为脉冲值或模数转换得到的值,需要乘以一个刻度系数才能转换成角速度或加速度值,若该系数不准,便存在刻度系数误差。 T 为交轴耦合误差 误差来源:如下图,b坐标系是正交的imu坐标系,s坐标系的三…

UE C++ 多镜头设置缩放 平移

一.整体思路 首先需要在 想要控制的躯体Pawn上&#xff0c;生成不同相机对应的SpringArm组件。其次是在Controller上&#xff0c;拿到这个Pawn&#xff0c;并在其中设置输入响应&#xff0c;并定义响应事件。响应事件里有指向Pawn的指针&#xff0c;并把Pawn的缩放平移功能进行…

暄桐教练日课·21天《线的初识》即将开始 一起感受线描的乐趣

林曦老师的直播课&#xff0c;是暄桐教室的必修课。而教练日课是丰富多彩的选修课&#xff0c;它会选出书法史/美术史上重要的、有营养的碑帖和画儿&#xff0c;与你一起&#xff0c;高效练习。而且暄桐教练日课远不止书法、国画&#xff0c;今后还会有更多有趣的课程陆续推出&…

Python | Leetcode Python题解之第214题最短回文串

题目&#xff1a; 题解&#xff1a; class Solution:def shortestPalindrome(self, s: str) -> str:n len(s)fail [-1] * nfor i in range(1, n):j fail[i - 1]while j ! -1 and s[j 1] ! s[i]:j fail[j]if s[j 1] s[i]:fail[i] j 1best -1for i in range(n - 1,…

Django之项目开发(二)

目录 一、安装和使用uWSGI 1.1、安装 1.2、配置文件 1.3、启动与停止uwsgi 二、安装nginx 三、Nginx 配置uWSGI 四、Nginx配置静态文件 五、Nginx配置负载均衡 一、安装和使用uWSGI uWSGI 是一个 Web 服务器,可以用来部署 Python Web 应用。它是一个高性能的通用的 We…

大模型备案全网最详细流程【附附件】

本文要点&#xff1a;大模型备案最详细说明&#xff0c;大模型备案条件有哪些&#xff0c;《算法安全自评估报告》模板&#xff0c;大模型算法备案&#xff0c;大模型上线备案&#xff0c;生成式人工智能(大语言模型)安全评估要点&#xff0c;网信办大模型备案。 大模型备案安…