Java-认识String

目录

一、String概念及创建

        1.1 String概念

         1.2 String的创建

二、String常用方法

        2.1 String对象的比较

        2.2  字符串查找

         2.3 转化

        2.4  字符串替换

        2.5 字符串拆分

         2.6字符串的截取

         2.7 其他操作方法

        2.8 字符串修改

三、面试题


一、String概念及创建

        1.1 String概念

                Java中字符串是由字符组成的一个字符数组,是复合数据类型,也是一种引用类型。所有涉及到可能修改字符串内容的操作都是创建一个新对象,改变的是新对象;String类中的字符实际保存在内部维护的value字符数组中
 

         1.2 String的创建

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

        //常量字符串构造

        String str="hello word";

        System.out.println(str);

        //new String对象

        String str1=new String("hello!");

        System.out.println(str1);

        //用字符数组构造

        char[] chars={'h','e','l','l','o',' ','w','o','r','l','d'};

        String str2=new String(chars);

        System.out.println(str2);

        

        注意:String是引用类型,内部并不存储字符串本身,而是存储一个地址,在Java中“”引起来的也是String类型对象。

        String s1="hello";

        String s2="world";

        String s3=s1;

        

 

二、String常用方法

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

        2.1 String对象的比较

                字符串的比较是常见操作之一,Java中提供了4中方式:

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

        int a=5;int b=10;//基本数据类型变量,==比较两个变量的值System.out.println(a==b);//引用类型变量,==比较两个引用变量引用是否为同一对象String s1="hello";String s2="world";String s3="hello";String s4=s1;System.out.println(s1==s2);System.out.println(s1==s3);System.out.println(s1==s4);

                

         2.boolean equals(Object anObject) 方法,比较字符串的内容是否相等,返回的是boolean类型。

        String s1 = new String("hello");String s2 = new String("hello");String s3 = new String("Hello");//s1、s2、s2引用对象不同,但s1和s2内容相同System.out.println(s1.equals(s2));System.out.println(s1.equals(s3));

                

                3.int compareTo(String s) 方法

                compareTo返回的是int类型,比较方式: 先按照字典次序大小比较,如果出现不等的字符,直接返回这两个字符的大小差值;如果前k个字符相等(k为两个字符长度最小值),返回两个字符串长度差值。

String s1=new String("abc");
String s2=new String("ac");
String s3=new String("abc");
String s4=new String("abcdef");
System.out.println(s1.compareTo(s2));//输出字符差值-1
System.out.println(s1.compareTo(s3));//输出0
System.out.println(s1.compareTo(s4));//输出长度差值-3

         4. int compareToIgnoreCase(String str) 方法:与compareTo方式相同,但是忽略大小写比较。

   String s1=new String("abc");String s2=new String("ac");String s3=new String("ABC");String s4=new String("abcdef");System.out.println(s1.compareToIgnoreCase(s2));//输出字符差值System.out.println(s1.compareToIgnoreCase(s3));//输出0System.out.println(s1.compareToIgnoreCase(s4));//输出长度差值

                

        2.2  字符串查找

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

方法功能
char charAt(int index)查找并返回index位置上字符,如果index为负数或者越界,抛出异常
int indexOf(int ch)查找并返回ch第一次出现的位置,没有返回-1
int indexOf(char ch, int fromIndex)

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

查找并返回str第一次出现的位置,没有返回-1

int indexOf(String str, int fromIndex)

从fromIndex位置开始找str第一次出现的位置,没有返回-1

int lastIndexOf(char 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
 
String s1="aabbccaabbcc";
System.out.println(s1.charAt(2)); //b
System.out.println(s1.indexOf('c'));  //4
System.out.println(s1.indexOf('b',4));  //8
System.out.println(s1.indexOf("bbcc"));     //2
System.out.println(s1.indexOf("bcc",4));  //9
System.out.println(s1.lastIndexOf('c'));    //11
System.out.println(s1.lastIndexOf('c',6));  //5
System.out.println(s1.lastIndexOf("bcc"));      //9
System.out.println(s1.lastIndexOf("bcc",8));  //3

         2.3 转化

                1.数字和字符串转化 String.valueOf、Integer.parseInt、Double.parseDouble

                //数字转字符串

        String s1=String.valueOf(15);String s2=String.valueOf(1.5);String s3=String.valueOf(true);System.out.println(s1);System.out.println(s2);System.out.println(s3);

                

         //字符串转数字,Integer、Double是Java中的包装类型

        int s1=Integer.parseInt("15");

        double s2=Double.parseDouble("1.5");

        System.out.println(s1);

        System.out.println(s2);

                2.大小写转换 toUpperCase、toLowercase

public static void main(String[] args) {String s1="abc";String s2="ABC";//小写转化为大写System.out.println(s1.toUpperCase());//大写转化为小写System.out.println(s2.toLowerCase());
}

                

               3.字符串数组转化  toCharArray、new String()

    public static void main(String[] args) {String s1="hello";//字符串转化为字符数组char[] ch=s1.toCharArray();for (char ch1:ch) {System.out.println(ch1);}//字符数组转化为字符串String s2=new String(ch);System.out.println(s2);
}

                

                 4.格式化  format

      public static void main(String[] args) {String s=String.format("%d-%d-%d",2023,8,7);System.out.println(s);}

                

 

        2.4  字符串替换

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

方法功能
String replaceAll(String regex, String replacement)替换所有的指定内容
String replaceFirst(String regex, String replacement)替换首个指定内容
public static void main(String[] args) {String s1="helloworld";String s2=s1.replaceAll("|","_");System.out.println(s2);String s3=s1.replaceFirst("|","_");System.out.println(s3);
}

                

        2.5 字符串拆分

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

方法功能
String[] split(String regex)将字符串全部拆分
String[] split(String regex, int limit)将字符串以指定格式拆分为limit组
        public static void main(String[] args) {String s1="hello word good afternoon";String[] s2=s1.split(" ");//全部拆分for (String str:s2) {System.out.println(str);}}

                          

        public static void main(String[] args) {String s1="hello word good afternoon";String[] s2=s1.split(" ",2);//拆分为两部分for (String str:s2) {System.out.println(str);}}

                 

         有些特殊字符作为分割符可能无法正确切分, 需要加上转义。

        例如:拆分IP地址

        String str = "192.168.1.1" ;
        String[] result = str.split("\\.") ;
        for(String s: result) {
        System.out.println(s);

        }

        

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

        多次拆分

public static void main(String[] args) {String str = "name=zhangsan&age=18";String[] s1=str.split("&");for (int i = 0; i < s1.length; i++) {String[]  s2=s1[i].split("=");for (String ch:s2) {System.out.println(ch);}}
}

                

         2.6字符串的截取

                从一个完整的字符串之中截取出部分内容。
                

方法功能
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(2,5));//左闭右开}

                        

         2.7 其他操作方法

                

方法功能
String trim()去掉字符串中的左右空格,保留中间空格

         String st=" hello world ";

         System.out.println("["+st+"]");

         System.out.println("["+st.trim()+"]");

           trim 会去掉字符串开头和结尾的空白字符(空格, 换行, 制表符等).

                   

        2.8 字符串修改

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

public static void main(String[] args) {
        String s = "hello";
        s += " world";
        System.out.println(s); // 输出:hello world
}

                这种方式不推荐使用,如果要修改建议尽量使用StringBuffer或者StringBuilder。

三、面试题

        1. String、StringBuffer、StringBuilder的区别

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

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

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Qt能跨多少个平台?Qt能支持多少个平台?

2023年8月5日&#xff0c;周日下午 目录 Qt所支持的平台更多关于Qt支持的信息 Qt所支持的平台 图中显示的平台都支持。 想要更详细的平台支持信息可以查看&#xff1a;Supported Platforms | Qt 5.15 更多关于Qt支持的信息 Qt - 支持的平台及语言

sentinel组件

目录 定义 4.加SentinelResource,blockHander是超过阈值之后执行的函数 5.设置阈值 6.springboot集成sentinel 定义 1.sentinel知道当前流量大小&#xff0c;在浏览器和后端之间加sentinel控制流量&#xff0c;避免大批量的瞬时请求都达到服务上&#xff0c;将服务压垮 2.…

第一天 什么是CSRF ?

✅作者简介&#xff1a;大家好&#xff0c;我是Cisyam&#xff0c;热爱Java后端开发者&#xff0c;一个想要与大家共同进步的男人&#x1f609;&#x1f609; &#x1f34e;个人主页&#xff1a;Cisyam-Shark的博客 &#x1f49e;当前专栏&#xff1a; 每天一个知识点 ✨特色专…

VSCode如何在行内显示变量值

背景 在调试时&#xff0c;我们希望能够直接在代码行显示变量的值&#xff0c;而不是总是去侧边栏查看&#xff0c;如下这种&#xff0c;y12直接显示在代码行。那么VSCode中如何做呢 设置 VSCode提供了“inline values”设置&#xff0c;但为了速度&#xff0c;默认并没有开…

在 React 中渲染大型数据集的 3 种方法

随着 Web 应用程序变得越来越复杂&#xff0c;我们需要找到有效的方法来优化性能和渲染大型数据集。在 React 应用程序中处理大型数据集时&#xff0c;一次呈现所有数据可能会导致性能不佳和加载时间变慢。 虚拟化是一种通过一次仅呈现数据集的一部分来解决此问题的技术&#…

2023年8月实时获取地图边界数据方法,省市区县街道多级联动【附实时geoJson数据下载】

首先&#xff0c;来看下效果图 在线体验地址&#xff1a;https://geojson.hxkj.vip&#xff0c;并提供实时geoJson数据文件下载 可下载的数据包含省级geojson行政边界数据、市级geojson行政边界数据、区/县级geojson行政边界数据、省市区县街道行政编码四级联动数据&#xff0…

高速过孔同进同出后续来了!影响大不大由你们自己说

高速先生成员---黄刚 话说Chris在上篇文章的结尾留下的悬念&#xff0c;其实在上周的答题里&#xff0c;也有不少粉丝猜到了接下来要验证的内容。我们知道&#xff0c;任何两个结构如果距离变近了&#xff0c;容性就会增加&#xff0c;无论是孔和孔&#xff0c;线和线&#xf…

php-cgi.exe - FastCGI 进程超过了配置的请求超时时限

解决方案一&#xff1a; 处理(php-cgi.exe - FastCGI 进程超过了配置的请求超时时限)的问题 内容转载&#xff1a; 处理(php-cgi.exe - FastCGI 进程超过了配置的请求超时时限)的问题_php技巧_脚本之家 【详细错误】&#xff1a; HTTP 错误 500.0 - Internal Server Error C:…

Rust 编程小技巧摘选(7)

Rust 编程小技巧(7) 1. 结构体 Display trait 结构体的两种形式&#xff0c;对应的成员取法不同&#xff1b; 前者用 self.成员变量名 self.x, self.y&#xff1b;后者用 self.成员索引号 self.0, self.1, self.2, ...... use std::fmt::Display; use std::fmt::Result; us…

SQL Server数据库如何添加Oracle链接服务器(Windows系统)

SQL Server数据库如何添加Oracle链接服务器 一、在添加访问Oracle的组件1.1 下载Oracle的组件 Oracle Provider for OLE DB1.2 注册该组件1.2.1 下载的压缩包解压位置1.2.2 接着用管理员运行Cmd 此处一定要用管理员运行&#xff0c;否则会报错 二、配置环境变量三、 重启SQL Se…

快速上手React:从概述到组件与事件处理

前言 「作者主页」&#xff1a;雪碧有白泡泡 「个人网站」&#xff1a;雪碧的个人网站 「推荐专栏」&#xff1a; ★java一站式服务 ★ ★ React从入门到精通★ ★前端炫酷代码分享 ★ ★ 从0到英雄&#xff0c;vue成神之路★ ★ uniapp-从构建到提升★ ★ 从0到英雄&#xff…

【深度学习】SMILEtrack: SiMIlarity LEarning for Multiple Object Tracking,论文

论文&#xff1a;https://arxiv.org/abs/2211.08824 代码&#xff1a;https://github.com/WWangYuHsiang/SMILEtrack 文章目录 AbstractIntroductionRelated WorkTracking-by-DetectionDetection methodData association method Tracking-by-Attention Methodology架构概述外观…