Home > Java > javaTutorial > body text

What are the common methods for java string traversal?

王林
Release: 2023-05-03 15:46:06
forward
2051 people have browsed it

    1. Introduction

    Common data structures and data types, such as strings, trees, hash tables, stacks, queues, etc., we often When solving problems, you will encounter the situation of traversing them, so only by mastering these methods can you open up your mind to solve the problem when you encounter the problem. Only by mastering the moves can you formally solve the problem and have the possibility of completing the problem independently.

    2. Specific traversal method

    2.1 Use charAt()

    • length(): Return the length of this character sequence.

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

    Then we can traverse every character of the string from 0 to length-1 through a for loop.

    String str="2022 fight";
    for(int i=0;i < str.length();i++) {
    	 System.out.println(str.charAt(i)); 
    }
    Copy after login

    2.2 Use substring(i,i 1)

    • CharSequence subSequence(int beginIndex, int endIndex): Returns a character sequence that is a sub-sequence of the sequence sequence.

    So you can set beginIndex to i and endIndex to i 1, so that you can get one character each time.

    String str="2022 fight";
    for(int i=0;i < str.length();i++) {
     System.out.println(str.substring(i,i+1)); 
    }
    Copy after login

    2.3 Use toCharArray()

    • toCharArray(): Convert this string to a character array.

    In this way, you can convert the string into a character array first, and then use a for loop to traverse the array.

    String str="2022 fight";
    char[] s = str.toCharArray();
    for(int i=0;i < str.length();i++) {
    	System.out.println(s[i]);
    }
    Copy after login

    2.4 Use getBytes()

    • getBytes(): Encode String into a series of byte sequences and then store it in a byte array.

    This method can be used when you need to traverse byte types. This method is relatively uncommon.

    String str="2022 fight";
    byte[] b = str.getBytes();
    for(int i=0;i < str.length();i++) {
    	System.out.println(b[i]);
    }
    Copy after login

    The above is the detailed content of What are the common methods for java string traversal?. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template