Day 5: Basic Data Structures – Strings

Strings are one of the most commonly used data structures in programming, particularly in Java. They represent sequences of characters and provide various methods for manipulation. In this post, we’ll explore string manipulation in Java, discuss common operations, and provide example problems, including a palindrome check.

Overview of String Manipulation in Java

In Java, strings are represented by the String class, which is immutable. This means that once a string object is created, it cannot be modified. However, you can create new strings from existing ones using various methods. The String class provides numerous methods to manipulate strings effectively.

Common String Operations

  1. Substring: Extracting a part of a string. The substring method allows you to specify the starting and optional ending indices.Example in JavajavaCopy codeString str = "Hello, World!"; String sub = str.substring(7, 12); // "World"
  2. Concatenation: Joining two or more strings together. You can use the + operator or the concat method.Example in JavajavaCopy codeString str1 = "Hello"; String str2 = "World"; String result = str1 + " " + str2; // "Hello World"
  3. Length: Finding the number of characters in a string. The length method returns the length of the string.Example in JavajavaCopy codeString str = "Hello"; int length = str.length(); // 5
  4. Character Access: Accessing individual characters using the charAt method.Example in JavajavaCopy codeString str = "Hello"; char ch = str.charAt(0); // 'H'
  5. String Comparison: Comparing two strings using equals or compareTo.Example in JavajavaCopy codeString str1 = "Hello"; String str2 = "hello"; boolean isEqual = str1.equals(str2); // false

Example Problem: Palindrome Check

A common problem involving strings is checking whether a given string is a palindrome (reads the same forward and backward). We can achieve this by comparing the string to its reverse.

Implementation in Java

javaCopy codepublic class PalindromeChecker {
    public static boolean isPalindrome(String str) {
        String reversed = new StringBuilder(str).reverse().toString();
        return str.equals(reversed);
    }

    public static void main(String[] args) {
        String testStr = "radar";
        boolean result = isPalindrome(testStr);
        System.out.println(testStr + " is a palindrome: " + result); // Output: true
    }
}

Conclusion

Strings are a fundamental data structure in Java that allow for various operations and manipulations. Understanding how to work with strings effectively is essential for programming tasks involving text processing and data handling.

In our next post, we will delve into Basic Data Structures – Linked Lists, exploring their properties and operations. Stay tuned!

Also see: The Z Blogs

my other Blog: The Z Blog ZB