How do I insert a string to a StringBuffer?

package org.kodejava.lang;

public class StringBufferInsert {
    public static void main(String[] args) {
        StringBuffer buffer = new StringBuffer("kodeava");
        System.out.println("Text before        = " + buffer);

        //  |k|o|d|e|a|v|a|....
        //  0|1|2|3|4|5|6|7|...
        //
        // From the above sequence you can see that the index of the
        // string is started from 0, so when we insert a string in
        // the fourth offset it means it will be inserted after the
        // "e" letter. There are other overload version of this
        // method that can be used to insert other type of data such
        // as char, int, long, float, double, Object, etc.
        buffer.insert(4, "j");
        System.out.println("After first insert = " + buffer);

        // Here we insert a string to the StringBuffer at index 8
        buffer.insert(8, " examples");
        System.out.println("Final result       = " + buffer);
    }
}

The program will print the following output:

Text before        = kodeava
After first insert = kodejava
Final result       = kodejava examples

How do I remove some characters from a StringBuffer?

The example below show you to remove some elements of the StringBuffer. We can use the delete(int start, int end) method call to remove some characters from the specified start index to end end index. We can also remove a character at the specified index using the deleteCharAt(int index) method call.

package org.kodejava.lang;

public class StringBufferDelete {
    public static void main(String[] args) {
        String text = "Learn Java by Examples";

        // Creates a new instance of StringBuffer and initialize
        // it with some text.
        StringBuffer buffer = new StringBuffer(text);
        System.out.println("Original text  = " + buffer);

        // We'll remove a sub string from this StringBuffer starting
        // from the first character to the 10th character.
        buffer.delete(0, 10);
        System.out.println("After deletion = " + buffer);

        // Removes a char at a specified index from the StringBuffer.
        // In the example below we remove the last character.
        buffer.deleteCharAt(buffer.length() - 1);
        System.out.println("Final result   = " + buffer);
    }
}

Output of the program is:

Original text  = Learn Java by Examples
After deletion =  by Examples
Final result   =  by Example

How do I get char value of a string at a specified position?

The chartAt() method of the String class returns the char value at the specified index. An index ranges from 0 to length() - 1. If we specified an index beyond of this range a StringIndexOutOfBoundsException exception will be thrown.

These method use zero based index which means the first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

package org.kodejava.lang;

public class CharAtExample {
    public static void main(String[] args) {
        String[] colors = {"black", "white", "brown", "green", "yellow", "blue"};

        for (String color : colors) {
            // Get char value of a string at index number 3. We'll get the 
            // fourth character of each color in the array because the 
            // index is zero based.
            char value = color.charAt(3);
            System.out.printf("The fourth char of %s is '%s'.%n", color, value);
        }

    }
}

Here is the program output:

The fourth char of black is 'c'
The fourth char of white is 't'
The fourth char of brown is 'w'
The fourth char of green is 'e'
The fourth char of yellow is 'l'
The fourth char of blue is 'e'

How do I determine if a string match a pattern exactly?

If you want the entire string to match your regular expression pattern you can use the Matcher.matches() method. This method will return true if and only if entire input string matches with the matcher’s pattern.

If the pattern only needs to match the beginning of the string you can use the Matcher.lookingAt() method. You can find its example on the following address How do I check if a string starts with a pattern?.

package org.kodejava.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherMatchesExample {

    public static void main(String[] args) {
        String[] inputs = {
                "blue sky",
                "blue sea",
                "blue",
                "blue lagoon"
        };

        // Creates an instance of Pattern using the compile method.
        Pattern pattern = Pattern.compile("blue");

        int match = 0;
        for (String s : inputs) {
            // Creates a matcher that will match the given input
            // against this pattern.
            Matcher matcher = pattern.matcher(s);

            // Check if the input match the pattern exactly and
            // increment the match counter.
            if (matcher.matches()) {
                match++;
            }

        }

        System.out.println("Number of input matched: " + match);
    }
}

The code above will only match one input that match exactly with the pattern (“blue”), because the other three elements of the array has another word beside blue.

How do I get the extension of a file?

Below is an example that can be used to get the extension of a file. The code below assume that the extension is the last part of the file name after the last dot symbol. For instance if you have a file named data.txt the extension will be txt, but if you have a file named data.tar.gz the extension will be gz.

package org.kodejava.io;

import java.io.File;

public class FileExtension {
    private static final String EXT_SEPARATOR = ".";

    public static void main(String[] args) {
        File file = new File("data.txt");
        String ext = FileExtension.getFileExtension(file);
        System.out.println("Ext = " + ext);

        file = new File("F:/Temp/Data/data.tar.gz");
        ext = FileExtension.getFileExtension(file);
        System.out.println("Ext = " + ext);

        file = new File("F:/Temp/Data/HelloWorld.java");
        ext = FileExtension.getFileExtension(file);
        System.out.println("Ext = " + ext);
    }

    /**
     * Get the extension of the specified file.
     *
     * @param file a file.
     * @return the extension of the file.
     */
    private static String getFileExtension(File file) {
        if (file == null) {
            return null;
        }

        String name = file.getName();
        int extIndex = name.lastIndexOf(FileExtension.EXT_SEPARATOR);

        if (extIndex == -1) {
            return "";
        } else {
            return name.substring(extIndex + 1);
        }
    }
}