Illuminatiiiiii
12/31/2018 - 8:57 AM

Character Extraction from Strings

Java Library Ep. 2:

public class Main {

    public static void main(String[] args) {

        //Character Extraction - Getting characters out of a String object
        String s1 = "Larry";
        char letter = s1.charAt(2); //Gets a single character at a given index
        System.out.println(letter);

        String s2 = "I am a long string";
        char[] chars = new char[4]; //Must be long enough to account for the num of chars you will be extracting
        //Gets multiple chars from a String object.
        s2.getChars(7, 11, chars, 0); // 1: Where to begin 2: Index one higher than where to stop. 3: Where to put the result 4: What index the char array to put the result
        System.out.println(new String(chars));

        byte[] bytes= s2.getBytes();
        System.out.println(new String(bytes));

        char[] charArray = s2.toCharArray();
        System.out.println(charArray);

        // ---List---
        //charAt - Gets a single character at a given index
        //getChars - Gets multiple chars from a String object.
        //getBytes - Gets a byte array from a String object
        //toCharArray - Gets a char array from a String object

    }
}