timerring

05 Strings

January 7, 2024 · 3 min read
Tutorial
Java
If you have any questions, feel free to comment below. Click the block can copy the code.
And if you think it's helpful to you, just click on the ads which can support this site. Thanks!

1. Characters and Integers — ASCII Codes #

Each commonly used character corresponds to a number in -128 ~ 127, and the two can be converted to each other. Note: currently, negative numbers have no corresponding characters.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        char c = 'a';
        System.out.println((int)c);

        int a = 66;
        System.out.println((char)a);
    }
}

Common ASCII values: 'A'- 'Z' are 65 ~ 90, 'a' - 'z' are 97 - 122, and 0 - 9 are 48 - 57.

In Java, character literals must be enclosed in single quotes and string literals in double quotes. They are distinct. (Python and JS do not make this distinction.)

Characters can participate in arithmetic; they are treated as integers during operations:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int a = 'B' - 'A';
        int b = 'A' * 'B';
        char c = 'A' + 2;

        System.out.println(a); // 1
        System.out.println(b);
        System.out.println(c);
    }
}

2. The String Class #

Initialization:

String a = "Hello World";
String b = "My name is ";
String x = b;  // Stored at the same address
String c = b + "yxc";  // Strings can be concatenated with the plus sign
String d = "My age is " + 18;  // int is implicitly converted to the string"18"
String str = String.format("My age is %d", 18);  // Format a string, similar to sprintf in C++
String money_str = "123.45";
double money = Double.parseDouble(money_str);  // Convert String to double

Read-only variables cannot be modified; for example:

String a = "Hello ";
a += "World";  // Constructs a new string

Accessing characters in a String:

String str = "Hello World";
for (int i = 0; i < str.length(); i ++ ) {
    System.out.print(str.charAt(i));  // Can only read, not write
}

Common APIs:

  • length():Return the length
  • split(String regex):Split a string
  • indexOf(char c)、indexOf(String str)、lastIndexOf(char c)、lastIndexOf(String str):Search; return -1 if not found, otherwise return the corresponding index.
  • equals():Check whether two strings are equal; note that you cannot simply use ==
  • compareTo():Compare two strings lexicographically; a negative value means less than, 0 means equal, and a positive value means greater than
  • startsWith(): Check whether it starts with a given prefix
  • endsWith():Check whether it ends with a given suffix
  • trim():Remove leading and trailing whitespace
  • toLowerCase():Convert all characters to lowercase
  • toUpperCase():Convert all characters to uppercase
  • replace(char oldChar, char newChar):Replace characters
  • replace(String oldRegex, String newRegex):Replace strings
  • substring(int beginIndex, int endIndex):Return the substring in [beginIndex, endIndex)
  • toCharArray():Convert the string to a character array (a common use: when a string cannot be traversed directly, convert it to a char array and traverse that array with for(char c: cs)).

3. Input and Output #

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str1 = sc.next();  // Read a string; stop at whitespace such as a space or newline
        String str2 = sc.nextLine();  // Read an entire line; spaces do not stop input, but a newline does

        System.out.println(str1);  // Can print directly
        System.out.printf("%s\n", str2);  // Can also use formatted output, with %s representing a string
    }
}

4. StringBuilder and StringBuffer #

A String cannot be modified; each change (such as +) creates a new string. If you plan to modify a string, use StringBuilder or StringBuffer.

StringBuffer is thread-safe and slower; StringBuilder is not thread-safe and is faster.

StringBuilder sb = new StringBuilder("Hello ");  // Initialize
sb.append("World");  // Append a string
System.out.println(sb);

for (int i = 0; i < sb.length(); i ++ ) {
    sb.setCharAt(i, (char)(sb.charAt(i) + 1));  // Read and write characters
}

System.out.println(sb);

Common APIs:

  • reverse():Reverse the string

Related readings


<< prev | 04 Arrays Continue strolling 06 Functions | next >>

If you want to follow my updates, or have a coffee chat with me, feel free to connect with me: