Open In App

String Guide for Competitive Programming

Last Updated : 15 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Strings are a sequence of characters, and are one of the most fundamental data structures in Competitive Programming. String problems are very common in competitive programming contests, and can range from simple to very challenging. In this article we are going to discuss about most frequent string tips and tricks that will help a programmer during Competitive Programming.

Common Operations on String:

1. Taking Strings as Input:

C++
#include <iostream>
using namespace std;

int main() {

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    string word, sentence;
    // Input a single word 
    cout<<"Enter a word: ";
    cin >> word;
    cout<<endl;
    // Input a line (multiple words) 
    cin.ignore();
    cout<<"Enter a sentence: ";
    getline(cin, sentence);
    cout<<endl;
  
    cout << "word = " << word << "\n";
    cout << "sentence = " << sentence << "\n";
    
    return 0;
}
Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter a single word
        System.out.print("Enter a word: ");
        String word = scanner.next();

        // Prompt the user to enter a sentence
        System.out.print("Enter a sentence: ");
        scanner.nextLine(); // consume the newline character left after reading the word
        String sentence = scanner.nextLine();

        System.out.println("\nEntered word: " + word);
        System.out.println("Entered sentence: " + sentence);

        scanner.close();
    }
}
Python3
# Python code to read a word and a sentence from the user

def main():
    # Prompt the user to enter a single word
    word = input("Enter a word: ")

    # Prompt the user to enter a sentence
    sentence = input("Enter a sentence: ")

    # Display the entered word and sentence
    print("\nEntered word:", word)
    print("Entered sentence:", sentence)

if __name__ == "__main__":
    main()
C#
using System;

class Program
{
    static void Main()
    {
        string word, sentence;

        // Input a single word
        word = Console.ReadLine();

        // Input a line (multiple words)
        sentence = Console.ReadLine();

        Console.WriteLine($"word = {word}");
        Console.WriteLine($"sentence = {sentence}");
    }
}
Javascript
let word, sentence;

// Input a single word
word = prompt("Enter a single word:");

// Input a sentence (multiple words)
sentence = prompt("Enter a sentence:");

// Display the input
console.log("word = " + word);
console.log("sentence = " + sentence);
//This code is contributed by Prachi.

Output
Enter a word: 
Enter a sentence: 
word = 
sentence = 

2. Find the First and Last Occurrence of a Character in the String:

C++
#include <bits/stdc++.h>
using namespace std;

int main()
{

    string str = "Learn Competitive Programming with GFG!";
    size_t first = str.find('m'),
        last = str.find_last_of('m');
    if (first != string::npos)
        cout << "First occurrence of m is at index = "
            << first << "\n";
    if (last != string::npos)
        cout << "Last Occurrence of m is at index = "
            << last << "\n";
    return 0;
}
Java
import java.io.*;

class GFG {
    public static void main(String[] args)
    {
        String str
            = &quot;Learn Competitive Programming with GFG!&quot;;
        int first = str.indexOf('m'),
            last = str.lastIndexOf('m');
        if (first != -1)
            System.out.println(
                &quot;First Occurrence of m is at index = &quot;
                + first);
        if (last != -1)
            System.out.println(
                &quot;Last Occurrence of m is at index = &quot;
                + last);
    }
}
Python3
str = &quot;Learn Competitive Programming with GFG!&quot;
first = str.find('m')
last = str.rfind('m')
if first != -1:
    print(f&quot;First Occurrence of m is at index = {first}&quot;)
if last != -1:
    print(f&quot;Last Occurrence of m is at index = {last}&quot;)
C#
using System;

class Program
{
    static void Main()
    {
        string str = "Learn Competitive Programming with GFG!";

        int first = str.IndexOf('m');
        int last = str.LastIndexOf('m');

        if (first != -1)
            Console.WriteLine($"First occurrence of 'm' is at index = {first}");
        
        if (last != -1)
            Console.WriteLine($"Last occurrence of 'm' is at index = {last}");

       
       
    }
}
Javascript
let str = "Learn Competitive Programming with GFG!";
let first = str.indexOf('m');
let last = str.lastIndexOf('m');

if (first !== -1) {
    console.log(`First Occurrence of m is at index = ${first}`);
}

if (last !== -1) {
    console.log(`Last Occurrence of m is at index = ${last}`);
}

Output
First occurrence of m is at index = 8
Last Occurrence of m is at index = 25

3. Reverse a String:

C++
#include <bits/stdc++.h>
using namespace std;

int main()
{
    string str = "Learn Competitive Programming with GFG!";
    string rev(str.rbegin(), str.rend());
    cout << "Reverse = " << rev << "\n";
    return 0;
}
Java
/*package whatever //do not write package name here */

import java.io.*;

class GFG {
    public static void main(String[] args)
    {
        String str
            = &quot;Learn Competitive Programming with GFG!&quot;;
        StringBuilder rev = new StringBuilder();
        rev.append(str);
        rev.reverse();
        System.out.println(&quot;Reverse = &quot; + rev);
    }
}
Python3
str = &quot;Learn Competitive Programming with GFG!&quot;
print(f&quot;Reverse = {str[::-1]}&quot;)
C#
using System;
using System.Text;

class Program
{
    static void Main()
    {
        string str = "Learn Competitive Programming with GFG!";
        string reversed = ReverseString(str);
        
        Console.WriteLine("Reverse = " + reversed);
    }

    static string ReverseString(string input)
    {
        char[] charArray = input.ToCharArray();
        Array.Reverse(charArray);
        return new string(charArray);
    }
}
Javascript
// Declare a string variable
let str = "Learn Competitive Programming with GFG!";

// Reverse the string by converting it to an array of characters, reversing the array, and joining it back into a string
let rev = str.split('').reverse().join('');

// Display the reversed string
console.log("Reverse = " + rev);

Output
Reverse = !GFG htiw gnimmargorP evititepmoC nraeL

4. Append a character/string at the end of the String:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    string str = "Learn Competitive Programming with ";
    str.append("GFG!");
    cout << "New String = " << str << "\n";
    return 0;
}
Java
/*package whatever //do not write package name here */

import java.io.*;

class GFG {
    public static void main (String[] args) {
        StringBuilder str = new StringBuilder(&quot;Learn Competitive Programming with &quot;);
          str.append(&quot;GFG!&quot;);
          System.out.println(&quot;New String = &quot; + str);
    }
}
Python3
str = &quot;Learn Competitive Programming with &quot;
str = &quot;&quot;.join([str, &quot;GFG!&quot;])
print(f&quot;New String = {str}&quot;)
C#
using System;

class MainClass {
    public static void Main(string[] args) {
        string str = "Learn Competitive Programming with ";
        str += "GFG!";
        Console.WriteLine("New String = " + str);
    }
}
// this coe is contributed by utkarsh
Javascript
// Initialize a string variable
let str = "Learn Competitive Programming with ";

// Concatenate another string to the existing one using the += operator
str += "GFG!";

// Display the updated string
console.log("New String = " + str);

Output
New String = Learn Competitive Programming with GFG!

5. Sorting a string:

C++
#include <bits/stdc++.h>
using namespace std;

int main()
{
    string str = "Learn Competitive Programming with GFG!";
    sort(str.begin(), str.end());
    cout << "Sorted String = " << str << "\n";

    return 0;
}
Java
/*package whatever //do not write package name here */

import java.util.*;

class GFG {
    public static void main(String[] args)
    {
        String str
            = "Learn Competitive Programming with GFG!";
        char array[] = str.toCharArray();
        Arrays.sort(array);
        str = new String(array);
        System.out.println("Sorted String = " + str);
    }
}
Python3
str = "Learn Competitive Programming with GFG!"
str = "".join(sorted(str))
print(f"Sorted string = {str}")
C#
using System;

class MainClass
{
    public static void Main(string[] args)
    {
        string str = "Learn Competitive Programming with GFG!";
        
        // Convert the string to a char array, sort, and then convert back to string
        char[] charArray = str.ToCharArray();
        Array.Sort(charArray);
        string sortedStr = new string(charArray);

        Console.WriteLine("Sorted String = " + sortedStr);

        // Alternatively, using LINQ
        //string sortedStr = new string(str.OrderBy(c => c).ToArray());
        //Console.WriteLine("Sorted String = " + sortedStr);
    }
}
Javascript
let str = "Learn Competitive Programming with GFG!";
let sortedStr = str.split('').sort().join('');
console.log("Sorted String =", sortedStr);

Output
Sorted String =     !CFGGLPaaeeegghiiiimmmnnooprrrtttvw

6. Substring extraction:

C++
#include <bits/stdc++.h>
using namespace std;

int main()
{
    string str = "Learn Competitive Programming with GFG!";
    cout << "Substring from index 6 to 16 = "
        << str.substr(6, 11) << "\n";
    return 0;
}
Java
public class Main {
    public static void main(String[] args) {
        String str = "Learn Competitive Programming with GFG!";
        String sub = str.substring(6, 17); // Index 6 to 16
        System.out.println("Substring from index 6 to 16 = " + sub);
    }
}
Python3
str = "Learn Competitive Programming with GFG!"
substring = str[6:17]  # Index 6 to 16
print("Substring from index 6 to 16 =", substring)
C#
using System;

class MainClass {
    public static void Main (string[] args) {
        // Initialize a string
        string str = "Learn Competitive Programming with GFG!";
        
        // Extract substring from index 6 to 16 (11 characters)
        string substring = str.Substring(6, 11);
        
        // Display the extracted substring
        Console.WriteLine("Substring from index 6 to 16 = " + substring);
    }
}
JavaScript
// Main function
function main() {
    // Define the string
    const str = "Learn Competitive Programming with GFG!";
    
    // Extract substring from index 6 to 16
    const substring = str.substring(6, 17);

    // Print the extracted substring
    console.log("Substring from index 6 to 16 =", substring);
}

// Call the main function to execute the program
main();

Output
Substring from index 6 to 16 = Competitive

Competitive Programming Tips for Strings in C++:

1. Pass by reference:

We should always pass the reference of strings to avoid making copies of the original string which is quite inefficient.

C++
#include <iostream>
using namespace std;

// Pass by value
int countSpaceSlow(string str, int idx)
{
    if (idx == str.length())
        return 0;
    return countSpaceSlow(str, idx + 1)
        + (str[idx] == ' ' ? 1 : 0);
}

// Pass by reference
int countSpaceFast(string& str, int idx)
{
    if (idx == str.length())
        return 0;
    return countSpaceSlow(str, idx + 1)
        + (str[idx] == ' ' ? 1 : 0);
}

int main()
{
    string str = "Learn Competitive programming with GFG!";
    cout << countSpaceSlow(str, 0) << "\n";
    cout << countSpaceFast(str, 0) << "\n";
    return 0;
}
Java
public class Main {
    // Pass by value
    public static int countSpaceSlow(String str, int idx) {
        if (idx == str.length())
            return 0;
        return countSpaceSlow(str, idx + 1)
                + (str.charAt(idx) == ' ' ? 1 : 0);
    }

    // Pass by reference (Java doesn't have true pass-by-reference, but we can use mutable objects like StringBuilder)
    public static int countSpaceFast(StringBuilder str, int idx) {
        if (idx == str.length())
            return 0;
        return countSpaceSlow(str.toString(), idx + 1)
                + (str.charAt(idx) == ' ' ? 1 : 0);
    }

    public static void main(String[] args) {
        String str = "Learn Competitive programming with GFG!";
        System.out.println(countSpaceSlow(str, 0));
        System.out.println(countSpaceFast(new StringBuilder(str), 0));
    }
}
//This code is contributed by Monu.
Python
# Pass by value
def count_space_slow(string, idx):
    if idx == len(string):
        return 0
    return count_space_slow(string, idx + 1) + (string[idx] == ' ')

# Pass by reference (using a list)
def count_space_fast(string, idx):
    if idx == len(string):
        return 0
    return count_space_slow(string, idx + 1) + (string[idx] == ' ')

if __name__ == "__main__":
    string = list("Learn Competitive programming with GFG!")
    print(count_space_slow(string, 0))
    print(count_space_fast(string, 0))
JavaScript
// Pass by value
function countSpaceSlow(str, idx) {
    if (idx === str.length)
        return 0;
    return countSpaceSlow(str, idx + 1) + (str[idx] === ' ' ? 1 : 0);
}

// Pass by reference (not applicable in JavaScript)
// Just for the sake of consistency, we'll keep the function signature
function countSpaceFast(str, idx) {
    if (idx === str.length)
        return 0;
    return countSpaceSlow(str, idx + 1) + (str[idx] === ' ' ? 1 : 0);
}

let str = "Learn Competitive programming with GFG!";
console.log(countSpaceSlow(str, 0));
console.log(countSpaceFast(str, 0)); // No pass by reference in JavaScript, so same as countSpaceSlow

Output
4
4

2. push_back() vs + operator:

We should always use push_back() function instead of + operator, to add a character at the end of the string. This is because the time complexity of + operator depends on the length of the string O(N) whereas push_back() simply pushes the character at the end in O(1) time complexity. So, if we need to append characters in a loop, push_back() will have much better performance as compared to + operator.

C++
#include <iostream>
using namespace std;

// Slow because of + operator
string filterLowerCaseSlow(string str)
{
    string res = "";
    for (int i = 0; i < str.length(); i++) {
        if (str[i] >= 'a' && str[i] <= 'z')
            res += str[i];
    }
    return res;
}

// Fast because of push_back()
string filterLowerCaseFast(string& str)
{
    string res = "";
    for (int i = 0; i < str.length(); i++) {
        if (str[i] >= 'a' && str[i] <= 'z')
            res.push_back(str[i]);
    }
    return res;
}

int main()
{
    string str = "Learn Competitive programming with GFG!";
    cout << filterLowerCaseSlow(str) << "\n";
    cout << filterLowerCaseFast(str) << "\n";
    return 0;
}
Java
public class Main {

    // Slow because of concatenating strings using '+'
    public static String filterLowerCaseSlow(String str) {
        String res = "";
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z')
                res += str.charAt(i);
        }
        return res;
    }

    // Fast because of using StringBuilder's append() method
    public static String filterLowerCaseFast(String str) {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z')
                res.append(str.charAt(i));
        }
        return res.toString();
    }

    public static void main(String[] args) {
        String str = "Learn Competitive programming with GFG!";
        System.out.println(filterLowerCaseSlow(str));
        System.out.println(filterLowerCaseFast(str));
    }
}
Python3
class Main:
    @staticmethod
    # Slow because of concatenating strings using '+'
    def filter_lower_case_slow(string):
        res = ""
        for char in string:
            if 'a' <= char <= 'z':
                res += char
        return res

    @staticmethod
    # Fast because of using StringBuilder's append() method
    def filter_lower_case_fast(string):
        res = []
        for char in string:
            if 'a' <= char <= 'z':
                res.append(char)
        return ''.join(res)

    @staticmethod
    def main():
        string = "Learn Competitive programming with GFG!"
        print(Main.filter_lower_case_slow(string))
        print(Main.filter_lower_case_fast(string))


# Call the main function to execute the program
Main.main()
JavaScript
// Slow because of concatenating strings using '+'
function filterLowerCaseSlow(str) {
    let res = "";
    for (let i = 0; i < str.length; i++) {
        if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z')
            res += str.charAt(i);
    }
    return res;
}

// Fast because of using StringBuilder's append() method
function filterLowerCaseFast(str) {
    let res = '';
    for (let i = 0; i < str.length; i++) {
        if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z')
            res += str.charAt(i);
    }
    return res;
}

const str = "Learn Competitive programming with GFG!";
console.log(filterLowerCaseSlow(str));
console.log(filterLowerCaseFast(str));

Output
earnompetitiveprogrammingwith
earnompetitiveprogrammingwith

Competitive Programming Tips for Strings in Java:

1. StringBuilder vs + operator:

Avoid using the + operator repeatedly when concatenating multiple strings. This can create unnecessary string objects, leading to poor performance. Instead, use StringBuilder (or StringBuffer for thread safety) to efficiently concatenate strings.

Java
import java.io.*;

class GFG {
    public static void main(String[] args)
    {
        // Slow Concatenation of Strings
        String str1 = &quot;&quot;;
        str1 = str1 + &quot;Hello&quot;;
        str1 = str1 + &quot; &quot;;
        str1 = str1 + &quot;World&quot;;
        System.out.println(str1);

        // Fast Concatenation of Strings
        StringBuilder str2 = new StringBuilder();
        str2.append(&quot;Hello&quot;);
        str2.append(&quot; &quot;);
        str2.append(&quot;World&quot;);
        System.out.println(str2);
    }
}

Output
Hello World
Hello World




















2. Use the equals() Method for String Comparison:

When comparing string content, use the equals() method or its variants (equalsIgnoreCase(), startsWith(), endsWith(), etc.) instead of the “==” operator, which compares object references.

Java
/*package whatever //do not write package name here */

import java.io.*;

class GFG {
    public static void main(String[] args)
    {
        String s1 = &quot;GFG&quot;, s2 = &quot;GFG&quot;;
        // Incorrect implementation
        System.out.println(s1 == s2);
        System.out.println(new String(&quot;GFG&quot;)
                           == new String(&quot;GFG&quot;));

        // Correct Implementation
        System.out.println(s1.equals(s2));
        System.out.println(
            new String(&quot;GFG&quot;).equals(new String(&quot;GFG&quot;)));
    }
}

Output
true
false
true
true




















Competitive Programming Tips for Strings in Python:

1. Use String Slicing and Concatenation Effectively.

String slicing is a powerful way to extract substrings from a string. You can use slicing to get individual characters, substrings of any length, or even reversed strings. String concatenation is used to join two or more strings together. There are two ways to concatenate strings in Python: using the + operator or the join() method. The + operator is more efficient for concatenating a small number of strings, while the join() method is more efficient for concatenating a large number of strings.

Python3
Str = &quot;Learn Competitive Programming &quot;
print(f&quot;First five characters = {Str[0:5]}&quot;)
print(f&quot;Reverse = {Str[::-1]}&quot;)

Str += &quot;with &quot;
Str = &quot;&quot;.join([Str, &quot;GFG!&quot;])

print(Str)

Output
First five characters = Learn
Reverse =  gnimmargorP evititepmoC nraeL
Learn Competitive Programming with GFG!




















2. Use Regular Expressions for Pattern Matching:

Regular expressions are a powerful tool for matching patterns in strings. Python has a built-in re module that provides regular expression support.

Python3
import re

# Method to find the number of words using Regex
def count_words(text):
    words = re.findall(r&quot;\w+&quot;, text)
    return len(words)


print(count_words(&quot;Learn Competitive Programming with GFG!&quot;))

Output
5




















Important String Algorithms for Competitive Programming:

Here are some important string algorithms for competitive programming:

String Algorithms

String hashing using Polynomial rolling hash function

Rabin-Karp Algorithm for Pattern Searching

KMP Algorithm for Pattern Searching

Z algorithm (Linear time pattern searching Algorithm)

Suffix Array Pattern Searching

Aho-Corasick Algorithm for Pattern Searching

Finite Automata algorithm for Pattern Searching

Boyer Moore Algorithm for Pattern Searching

Manacher’s Algorithm – Linear Time Longest Palindromic Substring




Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads