JAVA中String的常用方法

String类在所有项目开发里面一定会用到,因此String类提供了一系列的功能操作方法。

  1. 字符和字符串

    String类与字符之间的转换

    方法名称类型描述
    public String(char[]value)构造将字符数组转换为String类对象
    public String(char[]value,int offset,int count)构造将部分字符数组转换为String
    public char charAt(int index)普通返回指定索引对应的字符信息
    public char[] toCharArray()普通将字符串以字符数组的形式返回

    取出指定索引的字符-----使用charAt()方法

    package stringmethon;
    ​
    /**
     * 索引字符
     * 语法如下:public char charAt(int index)
     */
    public class StringDemo {
        public static void main(String[] args) {
            String str="hello";//定义字符串对象
            char c=str.charAt(0);//截取第一个字符
            System.out.println(c);//输出字符
        }
    ​
    }
    ​

    charAt()方法的主要作用是从一个字符串中截取指定索引的字符


    字符串和字符数组之间的转换_------使用toCharArray()方法

    package stringmethon;
    ​
    /**
     * 字符串和字符数组的转换
     * 将字符串以字符数组的形式返回语法如下:public char[] toCharArray()
     */
    public class String {
        public static void main(String[] args) {
            String str="hello";//定义字符串对象
            char[] data=str.toCharArray();//将字符串转换为字符数组
            //遍历字符数组,并循环输出每一个字符
            for (int i = 0; i < data.length; i++) {
                System.out.print(data[i]+"、");
            }
        }
    }
    ​

    本程序实现了字符串的拆分操作,利用toCharArray()方法可以将一个字符串拆分为字符数组,而拆分后的字符数组的长度就是字符串的长度。

  2. 字节和字符串

    字节使用byte描述,字节一般主要用于数据的传输或编码的转换,而在String类里面提供了将字符串转换为字节数组的操作,就是为了传输已经编码转换。


    字符串和字节数组转换的方法

    方法名称类型描述
    public String(byte[] bytes)构造将全部字节数组转换为字符串
    public String(byte[] bytes,int offest,int length)构造将部分字节数组转换为字符串
    public byte[] getBytes()普通将字符串变为字节数组
    public byte[] getBytes(String charsetName) throws UnsupportedEncodingException普通进行编码转换

    字符串和字节数组的转换------getBytes()方法

    package stringmethon;
    ​
    /**
     * 字符串和字节数组的转换
     */
    public class StringDemo {
        public static void main(String[] args) {
            String str="helloworld";//定义字符串对象
            byte[] data=str.getBytes();//将字符串转换为字节数组
            //遍历字节数组
            for (int i = 0; i < data.length; i++) {
                data[i]-=32;        //将小写字母变成大写
            }
            System.out.println(new String(data)); //全部转换
            System.out.println(new String(data,5,5));
        }
    }
    ​
  3. 字符串的比较

    字符串内容相等的方法

    方法名称类型描述
    -public boolean equals(String anObject)普通进行相等判断,区分大小写
    public boolean equalsIgnoreCase(String anoherString)普通进行相等判断,不区分大小写
    public int compareTo(String anotherString)普通判断两个字符串的大小(按照字符串编码进行比较)

    相等判断

    package stringmethon;
    ​
    /**
     * 相等判断
     * 区分大小写,语法如下:public boolean equals(String anObject)
     * 不区分大小写,语法如下:public boolean equalsIgnoreCase(String anotherString)
     */
    public class StringDemo {
        public static void main(String[] args) {
            String stra="hello"; //实例化字符串对象
            String strb="HELLO"; //实例化字符串对象
            System.out.println(stra.equals(strb));  //判断结果为flase
            System.out.println(stra.equalsIgnoreCase(strb));  //判断结果为true
        }
    }
    ​

    equals()方法和equalsIgnoreCase()方法只适合判断内容是否相等,前者区分大小写,后者不区分大小写,如果要比较两个字符串的大小关系,就必须使用compareTo()方法。

    compareTo()方法返回Int类型数据,这个int型数据有三种结果:大于(返回结果大于0)、小于(返回结果小于0)、等于(返回结果等于0)


    观察compareTo()方法

    package stringmethon;
    ​
    /**
     * 比较字符串的大小
     * 语法如下:public int compareTo(String anotherString)
     */
    public class StringDemo {
        public static void main(String[] args) {
            String stra="hello";  //实例化字符串对象
            String strb="iello";  //实例化字符串对象
            System.out.println(stra.compareTo(strb)); //比较两个字符串的大小
            if(stra.compareTo(strb)>0){
                System.out.println("大于0");
            }else if(stra.compareTo(strb)==0){
                System.out.println("等于0");
            }else{
                System.out.println("小于0");
            }
        }
    }
    ​

    compare()方法在比较字符串大小时,根据字符串数据的编码差值的方式来判断(如果第一个相同则继续后续内容判断)。如果要结合分支或循环语句来操作则可以利用compareTo()的返回结果数值来作为判断条件

  4. 字符串的查找

    方法名称类型描述
    public boolean contains(String s)普通判断指定字符串是否存在
    public int indexOf(String str)普通由前向后查找指定字符串的位置,如果查找到了则返回(第一个字母)位置索引,如果找不到返回-1
    public int indexOf(String str,int fromIndex)普通由指定位置从前向后查找指定字符串的位置,找不到返回-1
    public int lastIndexOf(String str)普通由后向前查找指定字符串的位置,找不到返回-1
    public int lastIndexOf(String str,int fromIndex)普通从指定位置从后向前查找字符串的位置,找不到返回-1
    public boolean startsWith(String prefix)普通判断是否以指定字符串开头
    public boolean startsWith(String prefix,int toffest)普通从指定位置开始判断是否以指定的字符串开头
    public boolean endsWith(String suffix)普通判断是否以指定字符串结尾

    使用indexOf()等功能查找

    package stringmethon;
    ​
    /**
     * 字符串查找
     */
    public class StringDemo {
        public static void main(String[] args) {
            String str="HelloWorld";//实例化字符串对象
            System.out.println(str.indexOf("World"));//返回满足条件的字符串的第一个字母的索引
            System.out.println(str.indexOf("l",7));//从第七个元素开始查找子字符串的位置
            System.out.println(str.indexOf("l"));//返回第一个查找到的子字符串的位置
            System.out.println(str.lastIndexOf("e"));//从后向前查找指定字符串的位置
            System.out.println(str.lastIndexOf("o",5));//从指定位置从后向前查找子字符串的位置
            //第一个输出5
            //第二个输出8
            //第三个输出2
            //第四个输出1
            //第五个输出4
    ​
        }
    }
    ​

    使用indexOf()方法判断字符串是否存在(通过判断查询结果是否为-1)来实现

    package stringmethon;
    ​
    /**
     * 用indexOf方法来判断字符串是否存在
     * 即判断查询结果是否为-1即可
     */
    public class StringDemo {
        public static void main(String[] args) {
            String str="helloworld";//实例化字符串对象
            if(str.indexOf("world")!=-1){
                System.out.println("可以查询到结果");
            }else{
                System.out.println("查询不到该字符串");
            }
        }
    }
    ​

    使用String扩充的contains()方法判断字符串是否存在

    package stringmethon;
    ​
    /**
     * 使用contain方法判读字符串是否存在
     */
    public class StringDemo {
        public static void main(String[] args) {
            String str="helloworld";
            if(str.contains("l")){
                System.out.println("可以查询到结果");
            }else{
                System.out.println("查询不到结果");
            }
        }
    }
    ​

    使用stratsWith()方法和endsWith()方法对字符串开头或结尾的进行判断

    package stringmethon;
    ​
    /**
     * 字符串开头和结尾的判断
     */
    public class StringDemo {
        public static void main(String[] args) {
            String str="&&helloworld***";//实例化字符串对象
            System.out.println(str.startsWith("&&"));//判断是否为&&开头
            System.out.println(str.startsWith("w",7));//从第七个索引判断是否以w开头
            System.out.println(str.endsWith("**"));//判断是否为**结尾
            //第一个返回结果为 true
            //第二个返回结果为 true
            //第三个返回结果为 true
        }
    }
    ​
  5. 字符串的替换

    方法名称类型描述
    public String replaceAll(String regex,String replacement)普通用新的内容替换全部旧的内容
    public String replaceFirst(String regex,String replacement普通替换首个满足条件的内容

    观察替换的结果

    package stringmethon;
    ​
    /**
     * 字符串的替换
     */
    public class StringDemo {
        public static void main(String[] args) {
            String str="helloworld";//实例化字符串对象
            String stra=str.replaceAll("l","*");//全部替换
            String strb=str.replaceFirst("l","&");//替换首个
            System.out.println(stra);
            System.out.println(strb);
    ​
            //程序执行结果为: he**owor*d
            //               he&loworld
    ​
        }
    }
    ​

    注意:这两个方法都会返回替换完成后的新字符串内容

  6. 字符串的截取

    从一个字符串中,可以取出指定的子字符串,称为字符串的截取操作

    方法名称类型描述
    public String substring(int beginIndex)普通从指定索引截取到结尾
    public String substring(int beginIndex,int endIndex)普通截取部分子字符串的数据

    截取子字符串

    package stringmethon;
    ​
    /**
     * 字符串的截取
     */
    public class StringDemo {
        public static void main(String[] args) {
            String str="helloworld";//实例化字符串对象
            String stra=str.substring(5);//从指定位置索引截取到结尾
            String strb=str.substring(0,5);//截取部分子字符串
            System.out.println(stra);
            System.out.println(strb);
    ​
            //程序执行结果为:world
            //             hello
        }
    }
    ​

    关于截取的参数设置

    在String类中substring()方法传递的参数只能是正整数,不能是负数,记住JAVA中的字符串索引是从0开始的。

  7. 字符串的拆分

    方法名称类型描述
    public String[] split(String regex)普通按照指定的字符串进行全部拆分
    public String[] split(String regex,int limit)普通按照指定的字符串进行部分拆分,最后的数组长度由limit决定(如果能拆分的结果很多,数组长度才会由limit决定),即前面拆,后面不拆

    进行全部拆分

    package stringmethon;
    ​
    /**
     * 字符串全部拆分
     */
    public class StringDemo{
        public static void main(String[] args) {
            String str="he ij wqs dwed sda f";//定义字符串,中间用空格隔开
            String[] data=str.split(" ");//字符串拆分
            //遍历数组
            for (int i = 0; i < data.length; i++) {
                System.out.print(data[i]+"、");
            }
        //程序执行结果为:he、ij、wqs、dwed、sda、f、
        }
    }
    ​

    如果使用空字符串则表示根据每个字符拆分(不是null)

    package stringmethon;
    ​
    /**
     * 字符串全部拆分
     */
    public class StringDemo {
        public static void main(String[] args) {
            String str="he ij wqs dwed sda f";//定义字符串,中间用空格隔开
            String[] data=str.split("");//字符串拆分
            //遍历数组
            for (int i = 0; i < data.length; i++) {
                System.out.print(data[i]+"、");
            }
        //程序执行结果为:h、e、 、i、j、 、w、q、s、 、d、w、e、d、 、s、d、a、 、f、
        }
    }
    ​

    拆分为指定个数

    package stringmethon;
    ​
    /**
     * 字符串指定个数拆分
     */
    public class StringDemo {
        public static void main(String[] args) {
            String str="diwd wf frew fwfc sac e c";//定义字符串,中间用空格隔开
            String[] data=str.split(" ",3);//字符串拆分
            //遍历数组
            for (int i = 0; i < data.length; i++) {
                System.out.println(data[i]);
            }
    //程序输出结果为:diwd
    //               wf
    //               frew fwfc sac e c
        }
    }
    ​

    实际上split()方法的字符串拆分能否正常进行,与正则表达式有关,所以有些时候会出现无法拆分的情况。例如:给出一个IP地址(192.168.1.2),那么肯定首先想的是根据"."进行拆分,而如果直接使用"."是不可能进行拆分的,如果想要正常执行,就必须对要拆分的". "进行转义,使用"\\"进行描述

    package stringmethon;
    ​
    /**
     * 转义操作进行拆分
     */
    public class StringDemo {
        public static void main(String[] args) {
            String str="192.168.1.2";//定义字符串
            String[] data=str.split("\\.");//字符串拆分
            //遍历数组
            for (int i = 0; i < data.length; i++) {
                System.out.print(data[i]+"、");
            }
            //程序执行结果为:192、168、1、2、
        }
    }
    ​

    复杂拆分

    package stringmethon;
    ​
    /**
     * 字符串的复杂拆分
     */
    public class StringDemo {
        public static void main(String[] args) {
            String str="张三:20|李四:21|王五:22";//定义字符串
            String[] data=str.split("\\|");//第一次拆分
            //遍历数组
            for (int i = 0; i < data.length; i++) {
                String[] temp=data[i].split(":"); //第二次拆分
                System.out.println("姓名:"+temp[0]+" "+"年龄:"+temp[1]);
            }
        }
    }
    //程序运行结果为:姓名:张三 年龄:20
    //              姓名:李四 年龄:21
    //              姓名:王五 年龄:22
  8. 其他方法

    方法名称类型描述
    public String concat(String str)字符串连接,与"+"类似
    public String toLowerCase()转小写
    public String toUpperCase()转大写
    public String trim()去掉字符串中左右变的空格,中间空格保留
    public int length()取得字符串长度
    public String intern()数据入池
    public boolean isEmpty()判断是否是空总字符串(不是null,而是"",长度0)

    字符串连接-----concat()方法

    package stringmethon;
    ​
    /**
     * 字符串连接
     * 语法如下:public String concat(String str)
     */
    public class StringDemo {
        public static void main(String[] args) {
            String str="hello";//定义字符串
            String stra=str.concat("world");//字符串连接
            System.out.println(stra);
        }
    }
    //程序运行结果为:helloworld

    本程序使用concat()方法实现字符串连接,但是大部分时候会被"+"所代替


    字符串转大小写

    package stringmethon;
    ​
    /**
     * 字符串转大小写的操作
     * 转小写:public String toLowerCase()
     * 转大写:public String toUpperCase()
     */
    public class StringDemo {
        public static void main(String[] args) {
            String str="***hello)))";//定义字符串
            System.out.println(str.toLowerCase());//转小写
            System.out.println(str.toUpperCase());//转大写
        }
    }
    //程序运行结果:***hello)))
    //             ***HELLO)))

    对于非字母的部分以上两个方法不会进行转换


    去掉左右空格——---trim()方法

    package stringmethon;
    ​
    /**
     * 去掉字符串左右两边空格
     * 语法如下:public String trim()
     */
    public class StringDemo {
        public static void main(String[] args) {
            String str="     hello   world    ";//定义字符串
            System.out.println("["+str+"]");
            System.out.println("["+str.trim()+"]");
        }
    }
    //程序运行结果为:[     hello   world    ]
    //               [hello   world]

    可以使用replaceAll()方法来实现空格删除,因为trim()方法只能删除左右两边的空格,不能将中间的删除

    package stringmethon;
    ​
    /**
     * 去掉字符串全部空格-----使用replaceAll()
     */
    public class StringDemo {
        public static void main(String[] args) {
            String str="    Hell0  World     ";//定义字符串
            System.out.println(str.replaceAll(" ",""));
        }
    }
    //程序运行结果:HelloWorld

    取得字符串的长度------length()方法

    package stringmethon;
    ​
    /**
     * 取得字符串长度
     * 语法如下:public int length()
     */
    public class StringDemo {
        public static void main(String[] args) {
            String str="helloworld";//定义字符串
            System.out.println(str.length());//取得字符串长度
        }
    }
    //程序运行结果为:10

    判断是否为空字符串------isEmpty()方法

    package stringmethon;
    ​
    /**
     * 判断是否为空字符串
     *语法如下:public boolean isEmpty()
     */
    public class StringDemo {
        public static void main(String[] args) {
            String str="helloworld";//定义字符串
            System.out.println(str.isEmpty());//判断字符串对象的内容是否为空字符串(不是null)
            System.out.println("".isEmpty());//判断字符串常量的内容是否为空字符串(不是null)
            System.out.println("".equals(str));
        }
    }
    //程序运行结果为:false
    //               true
    //               false

    空字符串指的是长度为0的字符串数据,不是null


    实现首字母大写,其他字母小写的方法-----=-----initcap()方法,只能自己实现

    package stringmethon;
    ​
    /**
     * 字符串首字母大写------initcap()
     */
    public class StringDemo {
        public static void main(String[] args) {
            String str="helloworld";//定义字符串
            System.out.println(initcap(str));
        }
        public static String initcap(String temp){
            //先利用substring方法截取第一个字符,再利用toUpperCase()方法将其转换为大写
            //最后将字符串连接起来就可以了
            return temp.substring(0,1).toUpperCase()+temp.substring(1);
        }
    }
    //程序运行结果为:Helloworld
  • 13
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值