Java之String

  • String
    字符串广泛应用在Java编程中,在Java中字符串属于对象,Java提供了String类来创建和操作字符串

  • 创建字符串

    格式:

String str = “Hello world!”;

注意:

1、字符串是常量;String类是不可改变的,所以你一旦创建了String对象,那它的值就无法改变了。 如果需要对字符串做很多修改,那么应该选择使用StringBuffer & StringBuilder 类。。
2、在代码中遇到字符串常量时,这里的值是”Hello world!”,编译器会使用该值创建一个String对象。
3、和其它对象一样,可以使用关键字和构造方法来创建String对象。

  • String的构造方法
    String类有16种构造方法,这些方法提供不同的参数来初始化字符串。

1、String()
初始化一个新创建的 String 对象,使其表示一个空字符序列。
2、String(byte[] bytes)
通过使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String。
3、String(byte[] bytes, Charset charset)
通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String。
4、String(byte[] ascii, int hibyte)
已过时。 该方法无法将字节正确地转换为字符。从 JDK 1.1 开始,完成该转换的首选方法是使用带有 Charset、字符集名称,或使用平台默认字符集的 String 构造方法。
5、String(byte[] bytes, int offset, int length)
通过使用平台的默认字符集解码指定的 byte 子数组,构造一个新的 String。
6、String(byte[] bytes, int offset, int length, Charset charset)
通过使用指定的 charset 解码指定的 byte 子数组,构造一个新的 String。
7、String(byte[] ascii, int hibyte, int offset, int count)
已过时。 该方法无法将字节正确地转换为字符。从 JDK 1.1 开始,完成该转换的首选方法是使用带有 Charset、字符集名称,或使用平台默认字符集的 String 构造方法。
8、String(byte[] bytes, int offset, int length, String charsetName)
通过使用指定的字符集解码指定的 byte 子数组,构造一个新的 String。
9、String(byte[] bytes, String charsetName)
通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String。
10、String(char[] value)
分配一个新的 String,使其表示字符数组参数中当前包含的字符序列。
11、String(char[] value, int offset, int count)
分配一个新的 String,它包含取自字符数组参数一个子数组的字符。
13、String(int[] codePoints, int offset, int count)
分配一个新的 String,它包含 Unicode 代码点数组参数一个子数组的字符。
14、String(String original)
初始化一个新创建的 String 对象,使其表示一个与参数相同的字符序列;换句话说,新创建的字符串是该参数字符串的副本。
15、String(StringBuffer buffer)
分配一个新的字符串,它包含字符串缓冲区参数中当前包含的字符序列。
16、String(StringBuilder builder)
分配一个新的字符串,它包含字符串生成器参数中当前包含的字符序列。

Sring的常用的构造方法:

public class TestString1 {

    public static void main(String[] args) {
        test1();
        test2();
        test3();
    }

    // 将字节数组转换为字符串
    public static void test1() {
        byte[] byteArray= {97,98,99};
        String s=new String(byteArray);
        System.out.println(s);
    }

    // 将字符数组转换为字符串
    public static void test2() {
        char[] charArray= {'a','b','c','d','e'};
        String s=new String(charArray);
        System.out.println(s);
    }

    // 将字符数组转换为字符串  cdef
    public static void test3() {
        byte[] byteArray= {97,98,99,100,101,102};
        String s=new String(byteArray,2,3);
        System.out.println(s);
    }

}

运行结果:

abc //对应的是ASCLL
abcde
cde
.

  • String的方法
    String类的方法是有许许多多的,在实际使用中根据自己的需求查看JavaAPI文档选择自己需要的方法

    下面是列举几个常用的String方法:

    1、equals和equalsIgnoreCase方法

boolean equals(Object anObject)
// 将此字符串与指定的对象比较。
boolean equalsIgnoreCase(String anotherString)
// 将此 String 与另一个 String 比较,不考虑大小写。

    public class StringText02 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String name="hex";
        String name0="lc";
        String name1="hex";
        String name2="HEX";
        System.out.println(name.equals(name0)); //equals方法
        System.out.println(name.equals(name1)); //equals方法
        System.out.println(name.equalsIgnoreCase(name2));//equalsIgnoreCase方法
    }

}

运行结果:

false
true
true

提示:
==号和equals方法的区别:

1)、 ==是一个比较运算符号,既可以比较基本数据类型,也可以比较引用数据类型,基本数据类型比较的是值,引用数据类型比较的是两个对象的内存地址。
2)、 equals方法是一个方法,只能比较引用数据类型,所有的对象都会继承Object类中的方法
3)、 通过查看Object类中的源码可知:如果没有重写Object类中的equals方法,equals方法和==号比较引用数据类型无区别。
小结
默认情况下equals比较的是两个对象的内存地址。 但是,这么做是什么多大意义的,所以一般都会重写后的equals方法;在重写的equals方法中比较的两个对象中的属性(成员变量)。

实例:

public static void main(String[] args) {
        String s1 = "hello world";    //在方法区的常量池中
        String s2 = "hello world";  //在方法区的常量池中

        String s3 = "hello" + " world"; //在方法区的常量池中

        String s4 = new String("hello world");  //在堆内存中
        String s5 = new String("hello world");  //在堆内存中

        System.out.println(s1 == s2);  // true
        System.out.println(s1.equals(s2));//true

        System.out.println("--------------");

        System.out.println(s1 == s3); //true
        System.out.println(s1.equals(s3)); //true

        System.out.println("--------------");

        System.out.println(s1 == s4);//false
        System.out.println(s1.equals(s4));//true

        System.out.println("--------------");

        System.out.println(s4 == s5);//false
        System.out.println(s4.equals(s5));//true



    }

}

运行结果:

true
true
--------------
true
true
--------------
false
true
--------------
false
true

2、concat( 将指定字符串连接到此字符串的结尾。返回一个新的字符串)

public class StringText04 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        testConcat();
    }
    public static void  testConcat() {// 将指定字符串连接到此字符串的结尾。
        String str1="Hello";
        String str2=str1.concat("-World");
        System.out.println(str2);
    }

}

运行结果:

Hello-World

3、contains( 当且仅当此字符串包含指定的 char 值序列时,返回 true。)

public class StringText04 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        testContains();
    }
public static void testContains() {//当且仅当此字符串包含指定的 char 值序列时,返回 true。)

        String s1="Hello9527";
        String s2="llo9527";
        boolean contains = s1.contains(s2);
        System.out.println(contains);
    }

运行结果:

true

3、startsWith()
`测试此字符串是否以指定的前缀开始。

public static void testStartsWith() {//startsWith

        String s1="Hello9527";
        boolean isStart=s1.startsWith("He");
        System.out.println(isStart);
    }

运行结果:

true

4、empty()
判断字符串是否为空

public static void testEmpty() {
        String s1="";
        boolean empty = s1.isEmpty();
        System.out.println(empty);
    }

运行结果:

true

5,length( ): 返回此字符串的长度
indexof( int ch ): 返回指定字符在此字符串中第一次出现处的索引。
charAt(int index)、 返回指定索引处的 char 值。
lastIndexOf(String str) : 返回指定子字符串在此字符串中最右边出现处的索引

public class TestString5 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        test1();
    }

    public static void test1() {
        String s="hello world";
        int length = s.length();
        System.out.println(length);
        char ch = s.charAt(4);
        System.out.println(ch);
        int index1 = s.indexOf('w');
        System.out.println(index1);
        int index2 = s.indexOf("ll");
        System.out.println(index2);
        int index3 = s.lastIndexOf("l");
        System.out.println(index3);
    }

}

运行结果:

11
o
6
2
9

6:

1) toUpperCase(Locale locale)
使用给定 Locale 的规则将此 String 中的所有字符都转换为大写。
2) toLowerCase(Locale locale)
使用给定 Locale 的规则将此 String 中的所有字符都转换为小写。

public static void test1() {
        String s="abcdefg";
        String upperCase = s.toUpperCase();
        System.out.println(upperCase);
    }

    public static void test2() {
        String s="ABCD";
        String lowerCase = s.toLowerCase();
        System.out.println(lowerCase);
    }

运行结果:

ABCDEFG
abcd

7:valueOf(int i)
返回 int 参数的字符串表示形式。

public static void test6() {
        int i=888;
        String intString = String.valueOf(i);
        System.out.println(intString);
    }

结果:

888

8)substring()

1):substring(int beginIndex)
返回一个新的字符串,它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始,直到此字符串末尾。
2)substring(int beginIndex, int endIndex)
参数:
beginIndex - 起始索引(包括)。
endIndex - 结束索引(不包括)。

public static void test1() {
        String s1="abcdefg1234dfwwwww";
        String s2=s1.substring(3);
        System.out.println(s2);
    }

    public static void test2() {
        String s1="abcdefghi1234567";
        String s2=s1.substring(1,4);
        System.out.println(s2);
    }

运行结果:

defg1234dfwwwww
bcd

9) trim()
返回字符串的副本,忽略前导空白和尾部空白。

public static void test3() {
        String s1="    abcdefghi1234567  ";
        System.out.println(s1.length());
        String s2 = s1.trim();
        System.out.println(s2.length());
        System.out.println(s2);
    }

运行结果:

22
16
abcdefghi1234567

10)replace()

replace(char oldChar, char newChar)返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。

public static void test4() {
        String s="hallo";
        String s2 = s.replace('a', 'e');
        System.out.println(s2);

        String s3 = s.replace('l', 'v');
        System.out.println(s3);
    }

    public static void test5() {
        String s="hello world";
        String replacedString = s.replace(" ", "");
        System.out.println(replacedString);
    }

运行结果:

hello
havvo
helloworld

String方法的具体应用
1:统计一个字符串中ab字符串的个数

public class StringMethod01 {

    public static void main(String[] args) {
        String str = "abcdefabc123ab66ababba";
        int count = 0;
        int index = 0;
        while((index = str.indexOf("ab"))!=-1){
            System.out.println(str);
            count++;
            str = str.substring(index+2);
        }
        System.out.println(count);

    }

}

运行结果:

abcdefabc123ab66ababba
cdefabc123ab66ababba
c123ab66ababba
66ababba
abba
5

应用2: 设计一个简单的登录系统

public static void login1() {
        while(true) {
        Scanner sc=new Scanner(System.in);
        System.out.println("Please input you name:");
        String name=sc.nextLine();

        //设置登录的条件

        if("Admin".equals(name)) {
            while(true) {
            System.out.println("Please input you password:");
            String pwd=sc.nextLine();
            if("123456".equals(pwd)) {
                System.out.println("恭喜您登录成功!!!");
                break;
            }   
                else {
                System.out.println("您输入的密码错误,请重新输入");
            }
        }
        }
        else {
            System.out.println("您登录用户名有错,请重新输入!!");
        }
    }
}

运行结果:

Please input you name:
Admin
Please input you password:
123456
恭喜您登录成功!!!
Please input you name:

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值