Java字符串String

        【char】类型代表字符类型,【String】类型代表字符串类型;

1.String类

1.1 声明字符串

        在Java中字符串必须包含在一对双引号(“ ")之内。双引号包含的都是字符串。

        声明字符串语法:

                String str;

//声明字符串语法
String str;        //声明字符串变量必须经过初始化赋值才能使用

String: 指定该变量为字符串类型;
str: 任意标识符;

1.2 创建字符串

1.2.1 String(char a[]): 

        用一个字符数组a创建String对象,使其表示字符数组参数中所有元素连接的结果。

char a[] = {'g', 'o', 'o', 'd'};
String s = new String(a);     
//或者 
String S = new String("good")

1.2.2 String(char a[],int offset,int length) :

        提取字符数组a中的一部分创建一个字符串对象,参数offset表示开始截取字符串的位置,length表示截取字符串的长度。

char a[] = {'g', 'o', 'o', 'd'};
String s = new String(a,1,2);     //或者 String s=new String("oo")

1.2.3 引用字符串常量来创建字符串变量

String str1,str2;
str1 = "we are students";
str2 = "we are students";
此时str1与str2引用相同的字符串常量,因此在内存中具有相同的实体。

此时str1与str2引用相同的字符串常量,因此在内存中具有相同的实体。

        

2.连接字符串

2.1 连接多个字符串

        使用【+】运算符可实现连接多个字符串的功能,并产生一个新的字符串

public class JoinString {
    public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("春田");
        String s3 = s1 + " " + s2;
        System.out.println(s3);
    }
}

输出:
hello 春田

2.2 连接其他数据类型

        字符串与其他基本数据类型相连接时,会将这些数据直接转换成字符串。

public class Link {
    public static void main(String[] args){
        int BookTime = 4;
        float Practice = 2.5f;
        //将字符串与整型,浮点型变量相连,并将结果输出
        System.out.println("我每天花费" + BookTime + "小时看书;" + Practice + "小时上机练习。");
    }
}

输出:
        我每天花费4小时看书;2.5小时上机练习。

3.获取字符串信息

3.1 获取字符串长度

        使用String类的length()方法获取声明的对象的长度。语法:

        str.length()

String str = "we are students";
int size = str.length();
System.out.println("str的长度是:" + size);

输出:
str的长度是:15

3.2 字符串查找

3.2.1 str.indexOf(substr)

        返回搜索的字符/字符串首次出现的索引位置;如果没有检索到字符串s,返回-1;

String str = "we are students";
int index = str.indexOf("a");
System.out.println(index);        //变量index的值是3

3.2.2 str.lastIndexOf(substr)

        从字符串的结尾处,从右向左反向查找指定的字符串。

        返回搜索的字符/字符串最后一次出现的索引位置;如果没有检索到字符串s,返回-1;

public class Text {
    public static void main(String[] args) {
        String str = "we are students";
        //将空字符串”“在str中的索引位置赋值给变量size
        int size = str.lastIndexOf("");
        System.out.println("空字符串”“在str中的索引位置是:" + size);
        System.out.println("字符串str的长度是:" + str.length());
    }
}

输出:
空字符串”“在str中的索引位置是:15
字符串str的长度是:15

3.3 获取指定索引位置的字符

        str.charAt(int index)

public class Ref {
    public static void main(String[] args) {
        String str = "hello chuntian!";
        char myChar = str.charAt(7);
        System.out.println("字符串str中索引位置7的字符为:" + myChar);
    }
}

输出:
字符串str中索引位置7的字符为:h

4.字符串操作

4.1 获取子字符串

4.1.1 str.substring(int beginIndex)

        此方法返回从指定的索引位置开始截取直到该字符串结尾的子串。

public class Ref {
    public static void main(String[] args) {
        String str = "hello world";
        String subStr = str.substring(3);
        System.out.println("subStr为:" + subStr);
    }
}

输出:
subStr为:lo world

4.1.2 str.substring(int beginIndex, int endIndex) 

         此方法返回从字符串某一索引位置开始截取直至某一索引位置结束的子串。

public class Ref {
    public static void main(String[] args) {
        String str = "hello world";
        String subStr = str.substring(0,3);
        System.out.println("subStr为:" + subStr);
    }
}

输出:
subStr为:hel

4.2 去除字符串前后空格

        str.trim()

public class Ref {
    public static void main(String[] args) {
        String str = "  hello world   ";
        System.out.println("字符串原来的长度为:" + str.length());
        System.out.println("字符串去掉前后空格的长度为:" + str.trim().length());
    }
}

输出:
字符串原来的长度为:16
字符串去掉前后空格的长度为:11

4.3 字符串替换

        str.replace(char oldChar, char newChar)

        返回的是一个新的字符串;如果oldChar没有出现在原字符串中,则将原字符串返回。

public class newStr {
    public static void main(String[] args) {
        String str = "address about";
        String newStr = str.replace("a", "A");
        System.out.println("newStr字符串为:" + newStr);
    }
}

输出:
newStr字符串为:Address About

4.4 判断字符串开始和结尾

        判断字符串的开始和结尾,皆返回boolean值。

4.4.1 str.startsWith(String prefix)

4.4.2 str.endsWith(String suffix)

public class newStr {
    public static void main(String[] args) {
        String str = "address about";
        boolean prefix = str.startsWith("a");
        boolean suffix = str.endsWith("a");
        System.out.println("字符串以a开头:" + prefix);
        System.out.println("字符串以a结尾:" + suffix);
    }
}

输出:
字符串以a开头:true
字符串以a结尾:false

4.5 判断字符串是否相等

        赋值运算符【=】比较的是值和地址是否相同;

        比较运算符【==】比较的是值是否相同;

String tom = new String("I am a student");
String jerry = new String("I am a student");
boolean result = (tom == jerry);
System.out.println(result);

输出:
false

 此处为false原因是:两个字符串是对象,jerry和tom只是两个字符串对象的引用,内存示意图:

4.5.1 str.equals(String otherstr)

        如果两个字符串具有相同的字符(区分大小写)和长度,则用equals()方法进行比较时,返回true;

4.5.2 str.equalsIgnoreCase(String otherstr) 

        equalsIgnoreCase()方法在忽略大小写的情况下比较两个字符串是否想相等,仍返回boolean类型;

public class Opinion {
    public static void main(String[] args) {
        String s1 = new String("abc");
        String s2 = new String("ABC");
        String s3 = new String("abc");
        //使用str.equals()比较字符串是否相等
        boolean b = s1.equals(s2);
        //使用str.equalsIgnoreCase()比较字符串是否相等
        boolean b2 = s1.equalsIgnoreCase(s2);
        System.out.println(s1 + "equals" + s2 + ":" + b);
        System.out.println(s1 + "equalsIgnoreCase" + s2 + ":" + b2);
    }
}

输出:
abc equals ABC:false
abc equalsIgnoreCase ABC:true

4.6 按字典顺序比较两个字符串

        str.compareTo(String otherstr)

        用的较少,忽略介绍。

4.7 字母大小写转换

4.7.1 str.toLowerCase()

4.7.2 str.toUpperCase()

        以上两个方法,若没有需要转换的字符,则将原字符串返回,若有需要转换的字符,则返回一个新的字符串。

public class UpAndLower {
    public static void main(String[] args) {
        String str = new String("abc DEF");
        String newStr = str.toLowerCase();
        String newStr2 = str.toUpperCase();
        System.out.println(newStr);
        System.out.println(newStr2);
    }
}

输出:
abc def
ABC DEF

4.8 分割字符串

        分割后的结果存放在字符串数组中。

4.8.1 str.split(String sign)

        sign为分割字符串的分割符,如果按照多个分割符分割,可使用符号【|】,例如:【”,| =“】表示分割符分别为【”,“】和【”=“】。

4.8.2 str.split(String sign, int limit)

        sign为指定的分割符;

        imit为限定的拆分次数;

public class Division {
    public static void main(String[] args) {
        String str = "192.168.0.1";
        //按照”.“进行分割,使用转义字符”\\.“
        String[] firstArray = str.split("\\.");
        //按照”.“进行分割2次,使用转义字符”\\.“
        String[] secondArray = str.split("\\.", 2);
        //输出原str值
        System.out.println("str的原值为:[" + str + "]");
        //输出全部分割的结果
        System.out.print("全部分割的结果:");
        for (String a : firstArray) {
            System.out.print("[" + a + "]");
        }
        System.out.println();   //换行
        //输出2次分割的结果
        System.out.print("两次分割的结果:");
        for (String a : secondArray) {
            System.out.print("[" + a + "]");
        }
        System.out.println();
    }
}

输出:
str的原值为:[192.168.0.1]
全部分割的结果:[192][168][0][1]
两次分割的结果:[192][168.0.1]

5.格式化字符串

String.format(String format, Object...args)

String.format(Local 1, String format, Object...args)

5.1 日期和时间字符串格式化

5.1.1 日期格式化

import java.util.Date;

public class Evald {
    public static void main(String[] args) {
        Date date = new Date(); //创建Date对象date
        String s = String.format("%te", date);   //通过format()方法对date进行格式化
        System.out.println("当前日期是:" + s);
    }
}

输出:
        当前日期是:11
常用的日期格式化转换符
转换符说明示例
%te一个月中的某一天(1~31)2
%td一个月中的第几天(01~31)02
%tb指定语言环境的月份简称Feb,二月
%tB指定语言环境的月份全称February,二月
%tA指定语言环境的星期几全称Monday,星期一
%ta指定语言环境的星期几简称Mon,星期一
%tc包括全部日期和时间信息星期二 十月 25 13:37:22 CST 2023
%tY4位年份2023
%ty2位年份23
%tm月份10
%tj一年中的第几天(001~366)085
import java.util.Date;

public class Evald {
    public static void main(String[] args) {
        Date date = new Date(); //创建Date对象date
        String year = String.format("%tY", date);   //获取年份
        String month = String.format("%tm", date);  //获取月份
        String day = String.format("%td", date);     //获取日期
        String all = String.format("%tc", date);     //获取全部日期和时间
        System.out.println("今年是:" + year + "年");
        System.out.println("现在是:" + month + "月");
        System.out.println("今天是:" + day + "号");
        System.out.println("完整时间是:" + all);
    }
}

输出:
        今年是:2023年
        现在是:10月
        今天是:11号
        完整时间是:星期三 十月 11 12:23:45 CST 2023

5.1.2 时间格式化

时间格式化转换符
转换符说明示例
%tH2位数字的24小时制的小时(00~23)14
%tk2位数字的24小时制的小时(0~23)5
%tI2位数字的12小时制的小时(01~12)05
%ti2位数字的12小时制的小时(1~12)10
%tM2位数字的分钟数(00~59)05
%tS2位数字的秒数(00~60)12
%tL3位数字的毫秒数(000~999)920
%tN9位数字的微秒数(000000000~999999999)062000000
%tp指定语言环境上午或下午的标记下午,pm
%tz相对于GMT RFC 82格式的数字时区偏移量+0800
%tZ时区缩写形式的字符串CST
%ts1970-01-01 00:00:00至现在经过的秒数1206426646
%tQ1970-01-01 00:00:00至现在经过的毫秒数1206426737453
import java.util.Date;

public class GetDate {
    public static void main(String[] args) {
        Date date = new Date();
        String hour = String.format("%tH", date);
        String minute = String.format("%tM", date);
        String second = String.format("%tS", date);
        System.out.println("当前时间是:" + hour + "时" + minute + "分" + second + "秒");
    }
}

输出:
        当前时间是:12时44分36秒

5.1.3 格式化常见的日期时间组合

常见的日期和时间组合的格式
转换符说明示例
%tF”年-月-日“格式(4位年份)2023-10-11
%tD”月/日/年“格式(2位年份)11/10/23
%tc全部日期和时间信息星期二 十月 25 13:37:22 CST 2023
%tr”时:分:秒 PM(AM)“格式(12时制)03:22:06 下午
%tR”时:分“格式(24时制)15:25
%tT”时:分:秒 “格式(24时制)15:25:50
import java.util.Date;

public class DateAndTime {
    public static void main(String[] args) {
        Date date = new Date();
        String time = String.format("%tc", date);
        String form = String.format("%tF", date);

        System.out.println("全部的时间信息是:" + time);
        System.out.println("年-月-日格式:" + form);
    }
}

输出:
        全部的时间信息是:星期三 十月 11 12:55:47 CST 2023
        年-月-日格式:2023-10-11

5.2 常规类型格式化

 常规转换符
转换符说明示例
%b,%B结果被格式化为布尔类型true
%h,%H结果被格式化为散列码A05A5198
%s,%S结果被格式化为字符串类型”abcdf“
%c,%C结果被格式化为字符类型’a‘
%d结果被格式化为十进制整数40
%o结果被格式化为八进制整数11
%x,%Z结果被格式化为十六进制整数4b1
%e结果被格式化为用计算机科学计数法表示的十进制数1.700000e+01
%a结果被格式化为带有效位数和指数的十六进制浮点值0X1.C000000000001P4
%n结果为特定平台的行分隔符
%%结果为字面值‘%’%
public class General {
    public static void main(String[] args) {
        String str = String.format("%d", 400 / 2);
        String str1 = String.format("%b", 3 > 5);
        String str2 = String.format("%x", 200);
        System.out.println("400的一半是:" + str);
        System.out.println("3>5正确吗?" + str1);
        System.out.println("200的十六进制数是:" + str2);
    }
}

输出:
        400的一半是:200
        3>5正确吗?false
        200的十六进制数是:c8

6.使用正则表达式

        正则表达式通常用于判断语句中,用于检查某一字符串是否满足某一格式。

正则表达式中的元字符
元字符正则表达式中的写法意义
..代表任意一个字符
\d\\d代表0~9的任何一个数字
\D\\D代表任何一个非数字字符
\s\\s代表空白字符,如’\t‘、’\n‘
\S\\S代表非空白字符
\w\\w代表可用作标识符的字符,但不包括'$'
\W\\W代表不可用于标识符的字符
\p{Lower}\\p{Lower}代表小写字母a~z
\p{Upper}\\p{Upper}代表大写字母A~Z
\p{ASCII}\\p{ASCII}ASCII字符
\p{Punct}\\p{Punct}标点符号:!"#$%&'()*+,-./:;<=>?@[\]^_’{|}~

        在正则表达式中”.“代表任意字符,因此如果想用普通意义的点字符”.“,必须使用转义符”\.“转义。

        在正则表达式中可以使用方括号[]括起若干个字符来表示一个元字符,该元字符可代表方括号内的任何一个字符,例如:reg = "[abc]4",代表a4,b4.c4都是和正则表达式匹配的字符串,语法:

        [^456]:代表4,5,6之外的任何字符;

        [a-r]:代表a~r中的任意一个字母;

        [a-zA-Z]:代表任意一个英文字母;

        [a-e[g-z]]:代表a~e或g~z中任意一个字母(并运算);

        [a-o&&[def]]:代表字母d,e,f (交运算);

        [a-d&&[^bc]]:代表字母a,d (差运算);

        在正则表达式中允许使用限定修饰符来限定元字符出现的次数,如”A*“代表”A“可以在字符串中出现0次或多次。

限定修饰符
限定修饰符意义示例
0次或1次A?
*0次或多次A*
+一次或多次A+
{n}正好出现n次A{2}
{n,}至少出现n次A{3,}
{n,m}出现n~m次A{2,6}
public class Judge {
    public static void main(String[] args) {
        //用正则表达式判断是否是合法的E-mail地址
        String email = "jeanet.t@outlook.com";
        String email1 = "jeanet.t@outlook.cn.com";
        String email2 = "xxx@";
        String email3 = "aaa";
        String regex = "\\w+((\\.)?\\w*)?@\\w+(\\.\\w{2,3})*\\.\\w{2,3}";

        if (email.matches(regex)) {
            System.out.println(email + "是一个合法的E-mail格式地址");
        } else {
            System.out.println(email + "非法");
        }
        if (email1.matches(regex)) {
            System.out.println(email1 + "是一个合法的E-mail格式地址");
        } else {
            System.out.println(email1 + "非法");
        }
        if (email2.matches(regex)) {
            System.out.println(email2 + "是一个合法的E-mail格式地址");
        } else {
            System.out.println(email2 + "非法");
        }
        if (email3.matches(regex)) {
            System.out.println(email3 + "是一个合法的E-mail格式地址");
        } else {
            System.out.println(email3 + "非法");
        }
    }
}

输出:
        jeanet.t@outlook.com是一个合法的E-mail格式地址
        jeanet.t@outlook.cn.com是一个合法的E-mail格式地址
        xxx@非法
        aaa非法

7.字符串生成器

7.1 StringBuilder类

        如果在程序中频繁的附加字符串,建议使用字符串生成器StringBuilder,新创建的StringBuilder对象初始容量是16个字节,并可自动增长长度以容纳被附加的字符,若StringBuilder要输出字符串结果,可用其toString()方法。StringBuilder类中的方法还有【appand()添加】,【insert()插入】,【delete()删除】,【toString()转换字符串】等编辑操作。

7.1.1 字符串生成器生成生成器对象

        StringBuilder builder = new StringBuilder("待生成的字符串xx")
public class Jerque {
    public static void main(String[] args) {
        //对比普通字符串附加和字符串生成器附加性能
        StringBuilder builder = new StringBuilder("");
        String str = "";
        long startTime1 = System.currentTimeMillis();
        for (int i = 0; i <= 10000; i++) {
            str = str + i;
        }
        long endTime1 = System.currentTimeMillis();
        long duration1 = endTime1 - startTime1;

        long startTime2 = System.currentTimeMillis();
        for (int j = 0; j <= 10000; j++) {
            builder.append(j);
        }
        long endTime2 = System.currentTimeMillis();
        long duration2 = endTime2 - startTime2;

        System.out.println("String消耗时长:" + duration1);
        System.out.println("StringBuilder消耗时长:" + duration2);
    }
}

输出:
        String消耗时长:127
        StringBuilder消耗时长:0

7.1.2 builder.append(content)方法

StringBuilder builder = new StringBuilder("");
for (int j = 0; j <= 10; j++) {
            builder.append(j);
        }
builder.toString()

7.1.3 builder.insert(int offset, arg)方法

StringBuilder builder = new StringBuilder("hello");
builder.insert(5,"world");
System.out.println(builder.toString());

输出:
helloworld

7.1.4 builder.delete(int start, int end)方法

StringBuilder builder = new StringBuilder("helloworld");
builder.delete(1,3);
System.out.println(builder.toString());

输出:
hloworld

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chuntian_tester

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值