Understanding Strings

In case you are learning DSA, you should definitely check out our free A2Z DSA Course with videos and blogs.

Strings are like a series of characters stored in a specific order. Each character in a string is assigned an index, starting from 0. This means the first character is at index 0, the second character at index 1, and so on.

Let’s take an example. Suppose we have a string s containing the word “striver.” If we want to access the character ‘s’, we can do so by using s[0], which corresponds to the first character. Similarly, s[1] will give us ‘t’, and s[2] will give us ‘r’. This zero-based indexing is a fundamental concept in working with strings.

Finding the Length of a String

To determine the length of a string, you can use the size or length function. These functions return the number of characters in the string. For example, if we have s as our string, you can find its length like this:

int len = s.size(); // or s.length();

Code:

C++ Code

#include <string>
#include <iostream>
using namespace std;

int main() {
    string small = "I am short";
    string large = "I, friend, am a long and elaborate string indeed";
    cout << "The short string is " << small.length() << " characters." << endl;
    cout << "The long string is " << large.length() << " characters." << endl;
    return 0;
}

Output:

The short string is 10 characters.
The long string is 48 characters.

Java Code

public class StringLengthExample {
    public static void main(String[] args) {
        String small = "I am short";
        String large = "I, friend, am a long and elaborate string indeed";
        System.out.println("The short string is " + small.length() + " characters.");
        System.out.println("The long string is " + large.length() + " characters.");
    }
}

Output:

The short string is 10 characters.
The long string is 48 characters.

Accessing Individual Characters

You can access individual characters within a string using square brackets, just like an array. Remember, positions start from 0. For instance:

Code:

C++ Code

#include <string>
#include <iostream>
using namespace std;

int main() {
    string test = "I am striv3r.";
    char ch = test[5]; // accessing the character ‘s’
    test[11] = 'e'; // Correcting a misspelling
    cout << test << endl;
    cout << "ch = " << ch << endl;
    return 0;
}

Output:

I am striver.
ch = s

Java Code

public class Main {
    public static void main(String[] args) {
        String test = "I am striv3r.";
        char ch = test.charAt(5); // accessing the character 's'
        StringBuilder sb = new StringBuilder(test);
        sb.setCharAt(10, 'e'); // Correcting a misspelling
        test = sb.toString();
        System.out.println(test);
        System.out.println("ch = " + ch);
    }
}

Output:

I am striver.
ch = s

Accessing the Last Character

With the knowledge of string length, you can easily access the last character. Remember, if a string has ‘n’ characters, the last character will be at index n-1. So, to access the last character of s, you can use s[len – 1], where len is the length of the string.

Code:

C++ Code

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s = "striver";
    int len = s.length();
    char lastChar = s[len - 1];
    cout << "The last character is: " << lastChar << endl;
    return 0;
}

Output:

The last character is: r

Java Code

public class Main {
    public static void main(String[] args) {
        String s = "striver";
        int len = s.length();
        char lastChar = s.charAt(len - 1);
        System.out.println("The last character is: " + lastChar);
    }
}

Output:

The last character is: r

Modifying a String

Strings are not just read-only; you can modify them as well. To change a character in a string, you must assign it a new character value. For example, if you want to change ‘t’ in s to ‘Z’, you can do so like this:

Remember, strings are made up of characters, so any modification should involve assigning a character to a specific index.

String Concatenation

Strings can be concatenated using the ‘+’ operator. This operator combines two strings into a single string. Here’s a concise example:

Code:

C++ Code

#include<iostream>
using namespace std;

int main(){
    string str1 = "Hey, ";
    string str2 = "Striver!";
    string result = str1 + str2; // Concatenate str1 and str2
    cout << result << endl;

    return 0;
   }

Output:

Hey,Striver!

Java Code

public class Main {
    public static void main(String[] args) {
        String str1 = "Hey, ";
        String str2 = "Striver!";
        
        // Concatenate str1 and str2 using the + operator
        String result = str1 + str2;
        
        System.out.println(result);
    }
}

Output:

Hey,Striver!

To achieve the functionality of concatenation of strings in Java, we use the StringBuilder class.

Passing, Returning, and Assigning Strings

Strings in C++ can be assigned and passed like primitive types. Assigning one string to another makes a deep copy of the character sequence:

Code:

C++ Code

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str1 = "hello";
    string str2 = str1; // Makes a new copy
    str1[0] = 'y'; // Changes str1, but not str2
    cout << "str1: " << str1 << endl;
    cout << "str2: " << str2 << endl;
    return 0;
}

Output:

str1: yello
Str2: hello

Java Code

public class Main {
    public static void main(String[] args) {
        String str1 = "hello";
        String str2 = str1; // Makes a new reference to the same string

        // Create a new string with the desired modification
        str1 = "y" + str1.substring(1);

        System.out.println("str1: " + str1);
        System.out.println("str2: " + str2);
    }
}

Output:

str1: yello
Str2: hello

In this code, str1 is assigned the value “hello,” and then str2 is assigned the value of str1. Despite modifying str1, str2 remains unaffected.

Passing Strings

In C++, strings can be seamlessly passed between functions. When you pass a string as an argument to a function, you’re essentially making a copy of the string. Any changes made to the string within the function won’t affect the original string outside of it.

Copying Strings

Copying strings is not merely a superficial process; it involves creating a new string with an identical character sequence. Whether you’re assigning a string to another or passing it to a function, you’re essentially creating a fresh copy.

String Comparison

The == known as the equality operator is used for comparing two values to check if they are equal. In programming, it’s commonly used to compare variables, such as numbers or strings, to determine if they have the same value. For example, x == y will return true if x is equal to y, and false otherwise.
The != known as the inequality operator is used to check if two values are not equal. It’s the opposite of the equality operator. If the values being compared are not equal, != returns true; if they are equal, it returns false.

Code:

C++ Code

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str1 = "Striver";
    string str2 = "Raj";
    string str3 = "Striver";

    // Equality check using == operator
    if (str1 == str2) {
        cout << "str1 is equal to str2" << endl;
    } else {
        cout << "str1 is not equal to str2" << endl;
    }

    // Inequality check using != operator
    if (str1 != str3) {
        cout << "str1 is not equal to str3" << endl;
    } else {
        cout << "str1 is equal to str3" << endl;
    }

    return 0;
}

Output:

str1 is not equal to str2
str1 is equal to str3

Java Code

public class StringComparison {
    public static void main(String[] args) {
      String str1 = "Striver";
      String str2 = "Raj";
      String str3 = "Striver";

        // Equality check using equals() method
        if (str1.equals(str2)) {
            System.out.println("str1 is equal to str2");
        } else {
            System.out.println("str1 is not equal to str2");
        }

        // Inequality check using equals() method
        if (!str1.equals(str3)) {
            System.out.println("str1 is not equal to str3");
        } else {
            System.out.println("str1 is equal to str3");
        }
    }
}

Output:

str1 is not equal to str2
str1 is equal to str3

Special thanks to Gauri Tomar for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article