Skip to content
The Chat Archive
gpt-3.5-turbo-0613· OpenAI WildChat-4.8M (AI2)

StringBuilde delete first char and last char java code

  1. User

    StringBuilde delete first char and last char java code

  2. Assistant

    Here's a Java code snippet using StringBuilder to delete the first and last characters from a string:

    public class Main {
        public static void main(String[] args) {
            StringBuilder sb = new StringBuilder("Hello World");
            System.out.println("Before: " + sb);
    
            sb.deleteCharAt(0);  // delete first character
            sb.deleteCharAt(sb.length() - 1);  // delete last character
    
            System.out.println("After: " + sb);
        }
    }
    

    The output will be:

    Before: Hello World
    After: ello Worl
    

    In this code, we create a StringBuilder object with the string "Hello World". Then, we use the deleteCharAt() method to delete the first character (index 0) and the last character (index sb.length() - 1). Finally, we print the modified string using System.out.println().