Home  >  Article  >  Java  >  Introduction to String operations in Java (code example)

Introduction to String operations in Java (code example)

不言
不言forward
2019-02-11 11:23:333107browse

This article brings you an introduction to String operations in Java (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. String operation String class

1. Overview

String is a special reference data type, it is final class.

2. Construction method

String str = "abc";

is equivalent to: char date[] = {'a','b ','c'};

String str = new String{data};

3. Main method

char charAt(int index) Returns the value at the specified index of char.

boolean contains(CharSequence s) returns true if and only if the string contains the specified char value sequence

boolean equals(Object anObject) Compares the substring with the specified object

int indexOf(int ch) Returns the index value of the first occurrence of the specified character

int length() Returns the length of the string, mostly used for the termination condition of the loop

boolean matches(String regex) Determine whether a string matches the given regular expression

String replace(char oldChar,char newChar) Replace all oldChar in the string with newChar

String split(String regex) Split the string according to the rules

String subString(int beginIndex) Returns the string after the beginindex index of the string

String toLowerCase() Returns all uppercase letters in the string Change to lowercase letters

String toUpperCase() Change all lowercase letters in the string to uppercase letters

String trim() Remove all leading and trailing spaces from the string and return

/*Type conversion*/
static String valueOf(boolean b)
Returns the string boolean form of the boolean parameter.
static String valueOf(char c)
Returns the string char form of the char parameter.
static String valueOf(char[] data)
Returns the string char form of the char array parameter.
static String valueOf(char[] data, int offset, int count)
Returns the string char form of a specific subarray of the char array parameter.
static String valueOf(double d)
Returns the string double form of the double parameter.
static String valueOf(float f)
Returns the string float form of the float parameter.
static String valueOf(int i)
Returns the string int form of the int parameter.
static String valueOf(long l)
Returns the string long form of the long parameter.
static String valueOf(Object obj)
Returns the string Object form of the Object parameter.

Note: The difference between the String string "==" and the equals method:

If it is declared through String str = "", both == and equals can be used;

If it is declared through new String (""), == cannot be used, only equals can be used.

4. Demonstration case

Requirement 1: Count the number of uppercase letters, lowercase letters and numbers in a string

Ideas : Convenience the string through a for loop, use the charAt method to obtain each character, and then compare each character with the value corresponding to the AsciI code to determine whether it is an uppercase letter, lowercase letter, or number, and print the count.

/**
 * @ author: PrincessHug
 * @ date: 2019/2/7, 17:09
 * @ Blog: https://www.cnblogs.com/HelloBigTable/
 */
public class StringAPIDemo {
    /**
     * 需求:计算字符串中大写字母、小写字母、数字出现的次数
     * @param args 参数
     */
    public static void main(String[] args) {
        //通过用户输入得到一个字符串
        String str = getString();
        getCount(str);
    }
    private static void getCount(String str) {
        int upperNum = 0;
        int lowerNum = 0;
        int digit = 0;
        for (int i = 0;i< str.length();i++){
            char c = str.charAt(i);
            /**
             * AscII码数字1-9(48-57),A-Z(65-91),a-z(97-123)
             */
            if (c>=48 && c<=57){
                digit++;
            }
            if (c>=65 && c<=91){
                upperNum++;
            }
            if (c>=97 && c<=123){
                lowerNum++;
            }
        }
        System.out.println("数字出现的次数为:" + digit);
        System.out.println("大写字母出现的次数为:" + upperNum);
        System.out.println("小写字母出现的次数为:" + lowerNum);
    }
    private static String getString() {
        System.out.println("请输入一个字符串:");
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        return s;
    }
}

Requirement 2: Query the number of times a certain substring appears in the parent string

Idea 1: Use the indexOf method to query the index a of the first occurrence of the substring, and then use subString The method returns the string after the parent string index (a substring length) and counts 1. Loop this operation until the return value of the indexOf method is -1 and stop, just get the count value.

Idea 2: Use the split method to split the parent string into substrings to obtain a String array. Use the subString method to obtain whether the last string of the parent string is equal to the substring. If so, return the String array. length; if not equal, the length-1 of the String array is returned.

**
 * @ author: PrincessHug
 * @ date: 2019/2/7, 17:34
 * @ Blog: https://www.cnblogs.com/HelloBigTable/
 */
public class FindChildStringCount {
    /**
     * 需求:查询父字符串中某一个子字符串的数量
     * @param args
     */
    public static void main(String[] args) {
        String parent = "itstar123qweritstar()%%dfitstarsdgji";
        String child = "itstar";

        int num1 = getChildStringCount01(parent, child);
        int num2 = getChildStringCount02(parent,child);
        int num3 = getChildStringCount03(parent,child);
        System.out.println("方法一:" + num1 + "次。");
        System.out.println("方法二:" + num2 + "次。");
        System.out.println("方法三:" + num3 + "次。");
    }

    private static int getChildStringCount02(String parent, String child) {
        String[] s = parent.split(child);
        if (child.equals(parent.substring(parent.length()-child.length()))){
            return s.length;
        }else {
            return s.length-1;
        }
    }

    private static int getChildStringCount01(String parent,String child) {
        int num = 0;
        int index = 0;
        while ((index = parent.indexOf(child)) != -1){
            num++;
            parent = parent.substring(index + child.length());
        }

        return num;
    }
    private static int getChildStringCount03(String parent,String child){
        String[] s = parent.split(child);
        int sum = 0;
        for (int i = 0;i < s.length;i++){
            sum += s[i].length();
        }
        return sum==parent.length()-(s.length-1)*child.length()?s.length-1:s.length;
    }
}

5.String rule matching (regular expression)

Regular expressions are often used to verify ID number, QQ number, email address, etc.

character classes and their meanings:

[abc] => abc can be used

[a- zA-Z] => A-z or A-Z can be used, both ends are closed intervals

[0-9] => The numbers 0-9 can be used

\d   => [0-9] Same as

\D  => It cannot be a number

\w  => It can represent letters, numbers, and underscores, equal to [a-zA-Z0-9_]

x? => Indicates that x appears once or not once

x*  => Indicates that x appears zero or more times

X{n} = > Indicates that x appears n times

X{n,m} => Indicates that x appears from n to m times

X

^  => Indicates the beginning of the regular expression

& => Indicates the end of the regular expression

Requirement 1: Verify whether the qq number is correct

qq number Conditions:

(1) digits are 5-15 digits

(2)开头数字不能为0

正则表达式为:regex = [1-9]\\d{4-14}

需求二:验证手机号码是否正确

手机号条件:

(1)位数为11位

(2)第一位为1

(3)第二位为3-9

正则表达式为:regex = [1]][3-9]\\d{9}  

需求三:验证邮箱是否正确

邮箱条件:

(1)@之前为邮箱名,字母、数字、下划线都可以

(2)@符号

(3)@之后为邮箱域名(qq.com/163.com.cn)

正则表达式为:regex = \\w+@[a-zA-Z0-9]+(\\.\\w{2,3})+

以下为需求一:验证qq号码是否正确,需求二、三只需将regex修改为对应的正则表达式即可。

/**
 * @ author: PrincessHug
 * @ date: 2019/2/7, 21:51
 * @ Blog: https://www.cnblogs.com/HelloBigTable/
 */
public class MatchQQ {
    public static void main(String[] args) {
        while (true) {
            String qq = getQQ();
            if (qq.equals("stop")){
                break;
            }else {
                matchQQ(qq);
            }
        }
    }

    /**
     * @return 返回获取的qq号
     */
    private static String getQQ() {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入您的qq号");
        String s = sc.nextLine();
        return s;
    }

    /**
     * 验证qq号是否匹配regex表达式
     * @param qq 获得用户输入的qq号
     */
    private static void matchQQ(String qq) {
        String regex = qqRegex();
        if (qq.matches(regex)) {
            System.out.println("QQ号正确!");
        } else {
            System.out.println("QQ号错误!");
        }
    }

    /**
     * @return 返回qq的正则表达式
     */
    private static String qqRegex() {
        String regex = "[1-9][0-9]{4,14}";
        return regex;
    }
}

The above is the detailed content of Introduction to String operations in Java (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete