Chapter 07 of 32

Strings in DSA

Strings are one of the most common types of data you'll work with in programming. A string is simply a sequence of characters.

For example:

String name = "John";

Here, "John" is a string made up of four characters:

J  o  h  n

Strings are extremely important in DSA because many problems involve searching, comparing, modifying, or analyzing text.

For example, you might be asked to check whether a word is a palindrome, count the vowels in a sentence, find duplicate characters, or check whether two strings are anagrams.

String as a Sequence of Characters

You can think of a string like an array of characters:

String: "John"

Index:   0   1   2   3
         ↓   ↓   ↓   ↓
         J   o   h   n

We can access individual characters using the charAt() method:

String name = "John";

System.out.println(name.charAt(0));

Output:

J

Similarly:

System.out.println(name.charAt(2));

Output:

h

Just like arrays, string indexing starts from 0.

Finding the Length

We can use the length() method to find the number of characters in a string.

String name = "John";

System.out.println(name.length());

Output:

4

Notice the difference between strings and arrays.

For an array:

numbers.length

For a string:

name.length()

The string version is a method.

Traversing a String

Since a string is a sequence of characters, we can use a loop to visit every character.

String name = "John";

for (int i = 0; i < name.length(); i++) {
    System.out.println(name.charAt(i));
}

Output:

J
o
h
n

This simple technique is used in many DSA problems involving strings.

Searching for a Character

Suppose we want to check whether a string contains the letter o.

We can use indexOf():

String name = "John";

System.out.println(name.indexOf('o'));

Output:

1

If the character doesn't exist, indexOf() returns -1.

System.out.println(name.indexOf('z'));

Output:

-1

We can also use contains() when searching for a sequence of characters:

String name = "John";

System.out.println(name.contains("oh"));

Output:

true

Comparing Strings

One of the most important things to understand in Java is that we generally compare strings using equals() rather than ==.

For example:

String name1 = "John";
String name2 = "John";

System.out.println(name1.equals(name2));

Output:

true

Using:

name1 == name2

is not the correct general way to compare string contents.

The equals() method checks whether the actual characters are the same.

We can also ignore uppercase and lowercase differences using equalsIgnoreCase():

String name1 = "John";
String name2 = "JOHN";

System.out.println(name1.equalsIgnoreCase(name2));

Output:

true

Reversing a String

Reversing a string is a very common beginner DSA problem.

Suppose we have:

John

We want:

nhoJ

One simple approach is to start from the last character and move toward the first:

String text = "John";
String reversed = "";

for (int i = text.length() - 1; i >= 0; i--) {
    reversed += text.charAt(i);
}

System.out.println(reversed);

Output:

nhoJ

This teaches an important DSA technique: processing data from the end toward the beginning.

For larger strings, repeatedly using + to build strings isn't ideal. A StringBuilder is often a better choice, which you'll use frequently in string problems.

Checking for a Palindrome

A palindrome is a word or sequence that reads the same forward and backward.

For example:

madam
level
radar

Let's check whether "madam" is a palindrome.

One simple approach is to reverse the string and compare it with the original:

String text = "madam";

String reversed = "";

for (int i = text.length() - 1; i >= 0; i--) {
    reversed += text.charAt(i);
}

if (text.equals(reversed)) {
    System.out.println("Palindrome");
} else {
    System.out.println("Not a palindrome");
}

Output:

Palindrome

This is a simple solution, although later we'll learn more efficient approaches using techniques such as two pointers.

Counting Characters

Suppose we want to count how many times the letter a appears.

String text = "banana";

int count = 0;

for (int i = 0; i < text.length(); i++) {
    if (text.charAt(i) == 'a') {
        count++;
    }
}

System.out.println(count);

Output:

3

The basic idea is:

Read each character
       ↓
Is it 'a'?
       ↓
Yes → increase count
       ↓
Continue

This kind of character counting appears in many DSA problems.

Converting a String

Java provides several useful methods for working with strings.

For example:

String name = "John";

Convert to uppercase:

System.out.println(name.toUpperCase());

Output:

JOHN

Convert to lowercase:

System.out.println(name.toLowerCase());

Output:

john

We can also remove spaces at the beginning and end using trim():

String text = "  Hello  ";

System.out.println(text.trim());

Strings Are Immutable

One important property of Java strings is that they are immutable.

That means once a String object is created, its contents cannot be changed.

For example:

String name = "John";

name = name.toUpperCase();

It might look like the original string was changed, but that's not what actually happened.

toUpperCase() creates a new string:

"John" → "JOHN"

and the variable name is then made to refer to the new string.

This is important to understand because you'll encounter it frequently when solving string problems.

String vs Character Array

A string can be converted into a character array using toCharArray().

For example:

String name = "John";

char[] characters = name.toCharArray();

Now we have:

J
o
h
n

This can be useful when we need to directly modify or rearrange individual characters.

For example:

char[] characters = "John".toCharArray();

characters[0] = 'B';

System.out.println(characters);

Output:

Bohn

StringBuilder for String Problems

Because strings are immutable, repeatedly creating new strings can be inefficient.

For example:

String result = "";

for (int i = 0; i < 1000; i++) {
    result += i;
}

This can create many intermediate string objects.

For situations where we're repeatedly modifying or building a string, StringBuilder is generally a better choice:

StringBuilder result = new StringBuilder();

for (int i = 0; i < 5; i++) {
    result.append(i);
}

System.out.println(result);

Output:

01234

We can also easily reverse it:

StringBuilder text = new StringBuilder("John");

text.reverse();

System.out.println(text);

Output:

nhoJ

Common String DSA Problems

Once you're comfortable with basic string operations, you'll encounter problems such as:

  • Reverse a string

  • Check whether a string is a palindrome

  • Count vowels and consonants

  • Count the frequency of characters

  • Find duplicate characters

  • Find the first non-repeating character

  • Check whether two strings are anagrams

  • Remove duplicate characters

  • Find the longest word

  • Find the longest substring

  • Check whether one string is a rotation of another

  • Find a substring inside a string

At first, these problems may look very different, but many of them are built from simple operations such as traversing characters, comparing characters, counting occurrences, and keeping track of positions.

A Complete Example

Let's write a simple program that counts vowels in a string:

class Main {
    public static void main(String[] args) {

        String text = "Hello John";

        int count = 0;

        for (int i = 0; i < text.length(); i++) {

            char ch = Character.toLowerCase(text.charAt(i));

            if (ch == 'a' || ch == 'e' ||
                ch == 'i' || ch == 'o' ||
                ch == 'u') {

                count++;
            }
        }

        System.out.println("Number of vowels: " + count);
    }
}

Output:

Number of vowels: 3

The program simply goes through every character and checks whether it is a vowel.

The Main Idea

In DSA, strings are best thought of as sequences of characters that we can process one character at a time.

The most important operations to become comfortable with are:

charAt()
length()
equals()
indexOf()
contains()
toCharArray()
StringBuilder

Once you are comfortable traversing strings and working with individual characters, you'll have a strong foundation for solving more advanced string problems.