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 sort string of numbers in ascending order?

In the following example we are going to sort a string containing the following numbers "2, 5, 9, 1, 10, 7, 4, 8" in ascending order, so we will get the result of "1, 2, 4, 5, 7, 8, 9, 10".

package org.kodejava.util;

import java.util.Arrays;

public class SortStringNumber {
    public static void main(String[] args) {
        // We have some string numbers separated by comma. First we
        // need to split it, so we can get each individual number.
        String data = "2, 5, 9, 1, 10, 7, 4, 8";
        String[] numbers = data.split(",");

        // Convert the string numbers into Integer and placed it into
        // an array of Integer.
        Integer[] intValues = new Integer[numbers.length];
        for (int i = 0; i < numbers.length; i++) {
            intValues[i] = Integer.parseInt(numbers[i].trim());
        }

        // Sort the number in ascending order using the
        // Arrays.sort() method.
        Arrays.sort(intValues);

        // Convert back the sorted number into string using the
        // StringBuilder object. Prints the sorted string numbers.
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < intValues.length; i++) {
            Integer intValue = intValues[i];
            builder.append(intValue);
            if (i < intValues.length - 1) {
                builder.append(", ");
            }
        }
        System.out.println("Before = " + data);
        System.out.println("After  = " + builder);
    }
}

When we run the program we will get the following output:

Before = 2, 5, 9, 1, 10, 7, 4, 8
After  = 1, 2, 4, 5, 7, 8, 9, 10

How do I get the content of an InputStream as a String?

We can use the code below to convert the content of an InputStream into a String. At first, we use FileInputStream create to a stream to a file that going to be read. IOUtils.toString(InputStream input, String encoding) method gets the content of the InputStream and returns a string representation of it.

package org.kodejava.commons.io;

import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;

public class InputStreamToString {
    public static void main(String[] args) throws Exception {
        // Create an input stream for reading data.txt file content.
        try (InputStream is = new FileInputStream("data.txt")) {
            // Get the content of an input stream as a string using UTF-8
            // as the character encoding.
            String contents = IOUtils.toString(is, StandardCharsets.UTF_8);
            System.out.println(contents);
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.12.0</version>
</dependency>

Maven Central

How do I determine whether a string is a palindrome?

This code checks a string to determine if it is a palindrome or not. A palindrome is a word, phrase, or sequence that reads the same backward as forward.

package org.kodejava.lang;

public class PalindromeChecker {

    public static void main(String[] args) {
        String text = "Sator Arepo Tenet Opera Rotas";

        PalindromeChecker checker = new PalindromeChecker();
        System.out.println("Is palindrome = " + checker.isPalindrome(text));
    }

    /**
     * This method checks the string for palindrome. We use StringBuilder to
     * reverse the original string.
     *
     * @param text a text to be checked for palindrome.
     * @return <code>true</code> if a text is palindrome.
     */
    private boolean isPalindrome(String text) {
        System.out.println("Original text = " + text);

        String reverse = new StringBuilder(text).reverse().toString();
        System.out.println("Reverse text  = " + reverse);

        // Compare the original text with the reverse one and ignoring its case
        return text.equalsIgnoreCase(reverse);
    }
}

How do I convert InputStream to String?

This example will show you how to convert an InputStream into String. In the code snippet below we read a data.txt file, could be from common directory or from inside a jar file.

package org.kodejava.io;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class StreamToString {

    public static void main(String[] args) throws Exception {
        StreamToString demo = new StreamToString();

        // Get input stream of our data file. This file can be in
        // the root of your application folder or inside a jar file
        // if the program is packed as a jar.
        InputStream is = demo.getClass().getResourceAsStream("/student.csv");

        // Call the method to convert the stream to string
        System.out.println(demo.convertStreamToString(is));
    }

    private String convertStreamToString(InputStream stream) throws IOException {
        // To convert the InputStream to String we use the
        // Reader.read(char[] buffer) method. We iterate until the
        // Reader return -1 which means there's no more data to
        // read. We use the StringWriter class to produce the string.
        if (stream != null) {
            Writer writer = new StringWriter();

            char[] buffer = new char[1024];
            try (stream) {
                Reader reader = new BufferedReader(new InputStreamReader(stream,
                        StandardCharsets.UTF_8));
                int length;
                while ((length = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, length);
                }
            }
            return writer.toString();
        }
        return "";
    }
}

How do I convert string into InputStream?

Here you will find how to convert string into java.io.InputStream object using java.io.ByteArrayInputStream class.

package org.kodejava.io;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class StringToStream {
    public static void main(String[] args) {
        String text = "Converting String to InputStream Example";

        // Convert String to InputStream using ByteArrayInputStream
        // class. This class constructor takes the string byte array
        // which can be done by calling the getBytes() method.
        InputStream stream = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));
    }
}

How do I split a string using Scanner class?

Instead of using the StringTokenizer class or the String.split() method we can use the java.util.Scanner class to split a string.

package org.kodejava.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerTokenDemo {
    public static void main(String[] args) {
        // This file contains some data as follows:
        // a, b, c, d
        // e, f, g, h
        // i, j, k, l
        File file = new File("data.txt");
        try {
            // Here we use the Scanner class to read file content line-by-line.
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();

                // From the above line of code we got a line from the file
                // content. Now we want to split the line with comma as the 
                // character delimiter.
                Scanner lineScanner = new Scanner(line);
                lineScanner.useDelimiter(",");
                while (lineScanner.hasNext()) {
                    // Get each split data from the Scanner object and print
                    // the value.
                    String part = lineScanner.next();
                    System.out.print(part + ", ");
                }                
                System.out.println();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

How do I compare string regardless of their case?

Here is an example of comparing two strings for equality without considering their case sensitivity. To do this we can use equalsIgnoreCase() method of the String class. Let’s see an example below:

package org.kodejava.basic;

public class EqualsIgnoreCase {
    public static void main(String[] args) {
        String uppercase = "ABCDEFGHI";
        String mixed = "aBCdEFghI";

        // To compare two string equality regarding it case use the
        // String.equalsIgnoreCase method.
        if (uppercase.equalsIgnoreCase(mixed)) {
            System.out.println("Uppercase and Mixed equals.");
        }
    }
}

How do I insert a string in the StringBuilder?

package org.kodejava.lang;

public class StringBuilderInsert {
    public static void main(String[] args) {
        StringBuilder alphabets = new StringBuilder("abcdfghopqrstuvwxyz");
        System.out.println("alphabets = " + alphabets);

        //  |a|b|c|d|f|g|h|i|....
        //  0|1|2|3|4|5|6|7|8|...
        //
        // 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 "d" 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.
        alphabets.insert(4, "e");
        System.out.println("alphabets = " + alphabets);

        // Here we insert an array of characters to the StringBuilder.
        alphabets.insert(8, new char[] {'i', 'j', 'k', 'l', 'm', 'n'});
        System.out.println("alphabets = " + alphabets);
    }
}

The result of the code snippet above:

alphabets = abcdfghopqrstuvwxyz
alphabets = abcdefghopqrstuvwxyz
alphabets = abcdefghijklmnopqrstuvwxyz

How do I remove substring from StringBuilder?

This example demonstrate you how to use the StringBuilder delete(int start, int end) and deleteCharAt(int index) to remove a substring or a single character from a StringBuilder.

package org.kodejava.lang;

public class StringBuilderDelete {
    public static void main(String[] args) {
        StringBuilder lipsum = new StringBuilder("Lorem ipsum dolor sit " +
                "amet, consectetur adipisicing elit.");
        System.out.println("lipsum = " + lipsum);

        // We'll remove a substring from this StringBuilder starting from
        // the first character to the 28th character.
        lipsum.delete(0, 28);
        System.out.println("lipsum = " + lipsum);

        // Removes a char from the StringBuilder. In the example below we
        // remove the last character.
        lipsum.deleteCharAt(lipsum.length() - 1);
        System.out.println("lipsum = " + lipsum);
    }
}

The result of the code snippet above:

lipsum = Lorem ipsum dolor sit amet, consectetur adipisicing elit.
lipsum = consectetur adipisicing elit.
lipsum = consectetur adipisicing elit