JavaSE 成长之路zijava学习

JavaSE基础(十二) - String 👾

2016-12-19  本文已影响227人  SawyerZh
String 字符串.png

今天学习了 Java 字符串的常用操作,写出来和简友们分享一下☺️
还是老规矩,先上思维导图。

1.String 概述

一起读 API 📖
public final class String extends Object
implements Serializable, Comparable<String>, CharSequence
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

通过查看 API 的概述我们可以知道以下几点:

字符内存图1

Reminder💁‍♂️:常量池中的值是不可被改变,但 String 对象是可以重指向的。


2.String 构造方法

一起读 API 📖
Constructs a new String by decoding the specified array of bytes using the platform's default charset.


3.String 面试题

String str1 = "abc";
String str2 = "abc";
System.out.println(str1 == str2);   // true
System.out.println(str1.equals(str2));  // true
字符串内存图2
String str1 = new String("abc");

一起读 API 📖
Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.

String str1 = new String(“abc”);
String str2 = “abc”;
System.out.println(str1 == str2);           // false
System.out.println(str1.equals(str2));  // true
String str1 = "a" + "b" + "c";
String str2 = "abc";
System.out.println(str1 == str2);           // true
System.out.println(str1.equals(str2));  // true
String str1 = "ab";
String str2 = "abc";
String str3 = str1 + "c";
System.out.println(str2 == str3);           // false
System.out.println(str2.equals(str3));  // true
字符串内存图3

一起读 API 📖
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java.


4.String 判断方法

Reminder💁‍♂️:比较是会判断大小写的。

Reminder💁‍♂️:如果 String == null 调用该方法会出现空指针异常


5.Test👨‍💻模拟登录功能

public class String_Test1 {

    private static Scanner sc = new Scanner(System.in);

    private static final String USER_NAME = "admin";

    private static final String PASSWORD = "admin";

    private static final int CHANCE_TIMES = 3;

    public static void test() {
        for (int i = 0; i < CHANCE_TIMES; i++) {
            System.out.print("Please enter user name: ");
            String userName = sc.nextLine();
            System.out.print("Please enter password: ");
            String password = sc.nextLine();
            // 用字符串常量去做比较,防止字符串变量为 null。
            if (USER_NAME.equals(userName) && PASSWORD.equals(password)) {
                System.out.println("Welcome " + userName + " login.");
                break;
            } else {
                // 今日试错次数用完,则给出提示。
                if (i == CHANCE_TIMES - 1) {
                    System.out.println("Today chance use up, please tomorrow login.");
                    break;
                }
                // 给出错误提示,并输出今日剩余试错次数。
                System.out.println("LoginFail: userName or password error.");
                System.out.println("You has " + (CHANCE_TIMES - 1 - i) + " times.");
            }
        }
    }
}

6.String 获取方法

Reminder💁‍♂️:我们的中文占 1 字符,转译符也占 1 字符。

Reminder💁‍♂️:StringIndexOutOfBoundsException 字符串索引越界异常

Reminder💁‍♂️:
可以传递 char 类型参数,因为会自动类型提升为 int
如果不存在则返回 -1

Reminder💁‍♂️:
如果不存在则返回 -1

Reminder💁‍♂️:包括当前索引 [fromIndex, ...]

Reminder💁‍♂️:[start, end) 左闭右开。


7.String 遍历

// 方式一
String str = "Sawyer";
for (int i = 0; i < str.length(); i++) {
    char ch = str.charAt(i);
    System.out.println(ch);
}
// 方式二
char[] arr_char = str.toCharArray();
    for (int i = 0; i < arr_char.length; i++) {
    System.out.println(arr_char[i]);
}

8.Test👨‍💻统计不同字符类型的个数

public static void test() {

    String str = "ABCDEabcd123456!@#$%";

    int lowerCaseCount = 0;
    int upperCaseCount = 0;
    int numberCount = 0;
    int otherCount = 0;

    for (int i = 0; i < str.length(); i++) {
        // String -> char[] 进行遍历
        char ch = str.charAt(i);
        if (ch >= 'a' && ch <= 'z') {
            lowerCaseCount++;
        } else if (ch >= 'A' && ch <= 'Z') {
            upperCaseCount++;
        } else if (ch >= '0' && ch <= '9') {
            numberCount++;
        } else {
            otherCount++;
        }
    }

    System.out.println("lowerCaseCount = " + lowerCaseCount + ", upperCaseCount = "
            + upperCaseCount + ", numberCount = " + numberCount +
            ", otherCount = " + otherCount + ".");
}

9.String 转换方法

Reminder💁‍♂️:
GBK 码表一个中文占用两个字节
中文的第一个字节是负数

Reminder💁‍♂️:
通过重载方法,可以将任意类型转换为字符串。
静态方法,底层是由 String 类的构造方法完成的。

Reminder💁‍♂️:
concat :只能对两个 String 做拼接操作。
+ :使用的更广泛。


10.String 其他方法

Reminder💁‍♂️:如果 oldChar 不存在,则保留原字符不改变。

String str1 = "abc";
String str2 = "abcd";
int str_compare = str1.compareTo(str2);
System.out.println(str_compare);        // -1

11.Test👨‍💻String关键字检索

public class String_Test8 {

    public static void test() {
        String source = "woailuchen,luchenbutongyuyaoyanhuo," +
                "wulunluchenhaishiyaoyanhuo,liaodelaidejiushihaobaobao";
        String target = "luchen";

        int count = targetCount(source, target);
        System.out.println(count);
        String mark_str = markStringAccordingTraget(source, target);
        System.out.println(mark_str);
    }

    // 获取检索关键字出现次数
    private static int targetCount(String source, String target) {
        int targetCount = 0;
        {
            // 从targetOffset关键字处开始检索
            int targetOffset = 0;
            while (true) {
                int targetIndex = source.indexOf(target, targetOffset);
                if (targetIndex == -1) {
                    break;
                } else {
                    // 改变将检索开始的fromindex
                    targetOffset = targetIndex + target.length();
                    targetCount++;
                }
            }
        }
        return targetCount;
    }

    // 将关键字用 "[]" 标记
    private static String markStringAccordingTraget(String source, String target) {
        return source.replace(target, " [ " + target + " ] " +
                "");
    }
}

悄悄话 🌈


彩蛋 🐣


上一篇下一篇

猜你喜欢

热点阅读