Strings, Char and Integer manipulation in Java

Divyanshi DixitDivyanshi Dixit
4 min read

When solving Data Structures and Algorithms (DSA) questions related to strings, I consistently have a conceptual understanding of manipulating input strings to achieve the desired output. However, leveraging the built-in methods or properties of the String class can significantly improve the process.

Here are some common tips and tricks I employ, and keeping these techniques handy can help me write code faster.

Char and Integers

  1. char to int

     char charValue = '9';
     int intValue = Character.getNumericValue(charValue); // Result: 9
    
  2. int to char

     int intValue = 65;
     char charValue = (char) intValue; // Result: 'A'
    
     // The below example is how you actually get the correct value in char
    
     int intValue = 1;
     char charValue = (char) (intValue + '0'); // Result: '1'
    
     // Another way to do the same
    
     int intValue = 1;
     char charValue = Character.forDigit(intValue, 10); // Result: '1'
     // The above method works if the int value lies between 1-9, if it is more than 9, then use string to store
    

Strings and Integers

  1. String to int conversion

     // Method - 1
     int signedPositiveExample = Integer.parseInt("+205"); // Result: 205
     // Method - 2
     int num = Integer.valueOf("344"); // Result: 344
    
  2. int to String Conversion

     // Method - 1
     int num = 15;
     String numAsString = Integer.toString(num); // Result: "15"
    
     // Method - 2 (with formatting)
     int hour = 9; // Example value
     String hourString = String.format("%02d", hour); // Result: "09"
     //The format specifier %02d indicates that the integer should be formatted with at least two digits, and if the number is less than two digits, it will be padded with leading zeros.
    

Chars and Strings

  1. String to Char array and Vice versa

     String s = "Hello"; // Example string
    
     // String to char array
     char[] arr = s.toCharArray(); // Result: ['H', 'e', 'l', 'l', 'o']
    
     // Char array to String [Method - 1]
     String str = String.valueOf(arr); // Result: "Hello"
    
     // Char array to String [Method - 2]
     char arr[] = new char[26];
     for(int i=0; i<s.length(); i++) 
         arr[s.charAt(i)-'a']++;
     String keyst = new String(arr);
    
  2. Single char to String

     // Method - 1
     char ch = 'A'; // Example character
     String str = String.valueOf(ch); // Result: "A"
    
     // Method - 2
     char ch = 'B'; // Example character
     String str = Character.toString(ch); // Result: "B"
    
  3. Check if a char is present in the string or not

     String str = "Hello, World!"; // Example string
    
     char ch1 = 'o'; // Example character to find
     int index1 = str.indexOf(ch1); // Result: 4
    
     char ch2 = 'z'; // Character not present in the string
     int index2 = str.indexOf(ch2); // Result: -1
    

Useful String Methods

  1. Get a substring of a string

     String oldString = "Hello, World!";
     int i = 0;
     int j = 5;
     String newString = oldString.substring(i, j); // Result: "Hello"
    
  2. Reverse a String

     String givenString = "abc";
     StringBuilder sb = new StringBuilder(givenString);
     sb.reverse(); // Result: "cba"
    
  3. Split String based on some delimiter

     String str = "This is a sentence";
     String[] strArr = str.split(" "); // Result: {"This", "is", "a", "sentence"}
    
  4. Save some integers in a string

     int a = 1, b = 2, c = 3, d = 4;
     String st = String.format("%d%d%d%d", a, b, c, d); // Result: "1234"
    
  5. Trim a string of its whitespaces

     String str = "   Trim me   ";
     String s = str.trim(); // Result: "Trim me"
    
  6. Check if two strings are equal

     String s1 = "Hello";
     String s2 = "Hello";
     boolean areEqual = s1.equals(s2); // Result: true
     // IMP Note: For StringBuffer and StringBuilder, use equals method for content equality, as == checks for object reference equality.
    

Useful StringBuilder Methods

  1. Insert at an index:
javaCopy codeStringBuilder sb = new StringBuilder("Hello, World!");
sb.insert(3, 'a'); // Result: "Heallo, World!"
  1. Add an Element:
javaCopy codeStringBuilder sb = new StringBuilder("Hello");
sb.append('d'); // Result: "Hellod"
  1. Add a string at the end:
javaCopy codeStringBuilder sb = new StringBuilder("Hello");
sb.append("abc"); // Result: "Helloabc"
  1. Get the start index of a string:
javaCopy codeStringBuilder sb = new StringBuilder("ABCDE");
int startIndex = sb.indexOf("BC"); // Result: 1
  1. Remove a particular string from StringBuilder:
javaCopy codeStringBuilder sb = new StringBuilder("Hello, World!");
sb.replace(7, 12, ""); // Result: "Hello!"
  1. Convert String to StringBuilder:
javaCopy codeString str = "Hello";
StringBuilder sb = new StringBuilder(str); // Result: StringBuilder with content "Hello"
  1. Convert StringBuilder to String:
javaCopy codeStringBuilder sb = new StringBuilder("Hello");
String str = sb.toString(); // Result: "Hello"
  1. Replace char with another char at an index:
javaCopy codeStringBuilder sb = new StringBuilder("Hello");
sb.setCharAt(3, 'a'); // Result: "Healo"

Thanks for reading, if you would like to connect with me, here is my LinkedIn profile - https://www.linkedin.com/in/divyanshi-dixit/

10
Subscribe to my newsletter

Read articles from Divyanshi Dixit directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Divyanshi Dixit
Divyanshi Dixit

I am a Software Engineer currently looking out for jobs around seattle, Washington.