gpt-3.5-turbo-0613· OpenAI WildChat-4.8M (AI2)
StringBuilde delete first char and last char java code
- User
StringBuilde delete first char and last char java code
- Assistant
Here's a Java code snippet using
StringBuilderto 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 WorlIn this code, we create a
StringBuilderobject with the string "Hello World". Then, we use thedeleteCharAt()method to delete the first character (index 0) and the last character (indexsb.length() - 1). Finally, we print the modified string usingSystem.out.println().