The Wayback Machine - https://web.archive.org/web/20240917114106/https://www.geeksforgeeks.org/basic-string-operations-with-implementation/
Open In App

Basic String Operations with Implementation

Last Updated : 08 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Easy
48.36%
7.2K

In this post, we will look into some of the basic String operations such as:

  • Accessing characters by index in a string.
  • Inserting character into a String.
  • Modifying character in String
  • Deletion of Character in String
  • Concatenating strings (combining multiple strings into one).
  • Finding the length of a string
  • Comparing strings for equality or lexicographical order

Let us consider the basic String operations one by one.

Accessing characters by index in a string.

To access any character in a String, we need:

  1. A non-empty string (say “str”)
  2. A position/index of the character from where it is to be accessed. (say “k”)

Using these two, the character can be easily accessed using the below syntax:

char ch = str[k];
OR
char ch = str.charAt(k);

Below is the implementation of the above approach:

C++
// CPP code for accessing an element by index

#include <iostream>
#include <string>

using namespace std;

// Function to demonstrate insert
char accessCharByIndex(string str, int k)
{

    // return the character at Kth index
    // in the string str
    return str[k];
}

// Driver code
int main()
{
    string str("GeeksforGeeks ");
    int k = 4;
    cout << accessCharByIndex(str, k) << endl;

    return 0;
}
C
#include <stdio.h>
#include <string.h>

// Function to demonstrate accessing character by index
char accessCharByIndex(char* str, int k)
{
    // Return the character at the kth index in the string
    return str[k];
}

// Driver code
int main()
{
    char str[] = "GeeksforGeeks ";
    int k = 4;
    printf("%c\n", accessCharByIndex(str, k));

    return 0;
}
Java
public class GFG {
  
    // Function to demonstrate accessCharByIndex
    public static char accessCharByIndex(String str, int k) {
      
        // Return the character at the k-th index in the string str
        return str.charAt(k);
    }

    // Driver code
    public static void main(String[] args) {
        String str = "GeeksforGeeks ";
        int k = 4;
        System.out.println(accessCharByIndex(str, k));
    }
}
Python
# Function to access an element by index
def access_char_by_index(s, k):
  
    # Return the character at the kth index in the string s
    return s[k]

# Driver code


def main():
    string_value = "GeeksforGeeks "
    index = 4
    print(access_char_by_index(string_value, index))


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

class Program {
  
    // Function to access a character by index
    static char AccessCharByIndex(string str, int k)
    {
      
        // Return the character at the k-th index
        return str[k];
    }

    static void Main()
    {
        string str = "GeeksforGeeks ";
        int k = 4;
        Console.WriteLine(AccessCharByIndex(str, k));
    }
}
JavaScript
// Function to demonstrate access by index
function accessCharByIndex(str, k) {
    // Return the character at the kth index in the string str
    return str[k];
}

// Driver code
let str = "GeeksforGeeks ";
let k = 4;
console.log(accessCharByIndex(str, k));

Output
s

Inserting Character/String into an String.

To insert any Character/String in a String, we need:

  1. A character/string that is to be inserted in the string (say “ch”)
  2. A position/index of the Character/String where it is to be inserted. (say “k”)

Below is the implementation of the above approach:

C++
// CPP code for Inserting character/string into an String.
#include <iostream>
#include <string>

using namespace std;

// Function to demonstrate insert
void insertDemo(string str, string ch, int k)
{

    // Inserts ch at kth index of str
    str.insert(k, ch);
    cout << "Modified String : " << str << endl;
}

// Driver code
int main()
{
    string str("GeeksGeeks ");
    string ch = "for";
    int k = 5;

    cout << "Original String : " << str << endl;
    insertDemo(str, ch, k);

    return 0;
}
C
#include <stdio.h>
#include <string.h>

void insertDemo(char* str, const char* ch, int k) {
    int len1 = strlen(str);
    int len2 = strlen(ch);

    // Shift characters to the right to make space for ch
    for (int i = len1; i >= k; i--) {
        str[i + len2] = str[i];
    }

    // Insert ch at kth index of str
    for (int i = 0; i < len2; i++) {
        str[k + i] = ch[i];
    }

    printf("Modified String: %s\n", str);
}

int main() {
    char str[] = "GeeksGeeks ";
    char ch[] = "for";
    int k = 5;

    printf("Original String: %s\n", str);
    insertDemo(str, ch, k);

    return 0;
}
Java
public class Main {
    public static void main(String[] args) {
        String str = "GeeksGeeks ";
        String ch = "for";
        int k = 5;

        System.out.println("Original String: " + str);
        insertDemo(str, ch, k);
    }

    // Function to demonstrate insert
    public static void insertDemo(String str, String ch, int k) {
        // Inserts ch at kth index of str
        StringBuilder sb = new StringBuilder(str);
        sb.insert(k, ch);
        String modifiedString = sb.toString();
        System.out.println("Modified String: " + modifiedString);
    }
}
Python
# Python program for the above approach

# Function to demonstrate insert
def insert_demo(s, ch, k):

    # Inserts ch at kth index of s
    modified_string = s[:k] + ch + s[k:]
    print("Modified String:", modified_string)

# Driver code
if __name__ == "__main__":
    original_string = "GeeksGeeks "
    ch_to_insert = "for"
    index_to_insert = 5

    print("Original String:", original_string)
    insert_demo(original_string, ch_to_insert, index_to_insert)

# This code is contributed by Susobhan Akhuli
C#
using System;

class Program
{
    // Function to demonstrate insert
    static string InsertDemo(string str, string ch, int k)
    {
        // Inserts ch at kth index of str
        return str.Insert(k, ch);
    }

    // Driver code
    static void Main()
    {
        string str = "GeeksGeeks ";
        string ch = "for";
        int k = 5;

        Console.WriteLine("Original String: " + str);
        string modifiedString = InsertDemo(str, ch, k);
        Console.WriteLine("Modified String: " + modifiedString);
    }
}
JavaScript
// JavaScript equivalent of the given Java code

// Function to demonstrate insert
function insertDemo(str, ch, k) {
    // Inserts ch at kth index of str
    let modifiedString = str.slice(0, k) + ch + str.slice(k);
    console.log("Modified String: " + modifiedString);
}

// Main function
function main() {
    let str = "GeeksGeeks ";
    let ch = "for";
    let k = 5;

    console.log("Original String: " + str);
    insertDemo(str, ch, k);
}

// Call the main function
main();

Output
Original String : GeeksGeeks 
Modified String : GeeksforGeeks 

Modifying character in String

To modify any Character in a String, we need:

  1. A character that is to replaced in the string (say “ch”)
  2. A position/index of the Character where it is to be replaced at. (say “k”)

Below is the implementation of the above approach:

C++
#include <iostream>
#include <string>

int main()
{
    // Get the string
    std::string str = "Geeks Gor Geeks";

    // Get the index
    int index = 6;

    // Get the character
    char ch = 'F';

    // Print the original string
    std::cout << "Original String = " << str << std::endl;

    str.replace(index, 1, 1, ch);

    // Print the modified string
    std::cout << "Modified String = " << str << std::endl;

    return 0;
}
C
#include <stdio.h>
#include <string.h>

int main()
{
    // Define the string
    char str[] = "Geeks Gor Geeks";

    // Define the index
    int index = 6;

    // Define the character
    char ch = 'F';

    // Print the original string
    printf("Original String = %s\n", str);

    // Modify the string
    str[index] = ch;

    // Print the modified string
    printf("Modified String = %s\n", str);

    return 0;
}
Java
public class GFG {

    public static void main(String args[])
    {

        // Get the String
        String str = "Geeks Gor Geeks";

        // Get the index
        int index = 6;

        // Get the character
        char ch = 'F';

        // Print the original string
        System.out.println("Original String = " + str);

        str = str.substring(0, index) + ch
            + str.substring(index + 1);

        // Print the modified string
        System.out.println("Modified String = " + str);
    }
}
Python
# Function to replace a character at a specific index in a string
def replace_character_at_index(string, index, new_character):

    # Convert string to list of characters to allow modification
    string_list = list(string)

    # Replace character at the specified index
    string_list[index] = new_character

    # Convert back to string and return
    return ''.join(string_list)

# Main function


def main():
    # Original string
    original_string = "Geeks Gor Geeks"

    # Index to replace character
    index = 6

    # New character
    new_character = 'F'

    # Print original string
    print("Original String =", original_string)

    # Replace character at the specified index
    modified_string = replace_character_at_index(
        original_string, index, new_character)

    # Print modified string
    print("Modified String =", modified_string)


# Entry point of the program
if __name__ == "__main__":
    main()
C#
using System;

public class GFG
{
    public static void Main()
    {
        // Get the String
        string str = "Geeks Gor Geeks";

        // Get the index
        int index = 6;

        // Get the character
        char ch = 'F';

        // Print the original string
        Console.WriteLine("Original String = " + str);

        // Modify the string
        str = str.Substring(0, index) + ch + str.Substring(index + 1);

        // Print the modified string
        Console.WriteLine("Modified String = " + str);
    }
}
JavaScript
let str = "Geeks Gor Geeks"; // Get the string
let index = 6; // Get the index
let ch = 'F'; // Get the character

console.log("Original String = " + str); // Print the original string

// Modify the string
str = str.substr(0, index) + ch + str.substr(index + 1);

console.log("Modified String = " + str); // Print the modified string

Output
Original String = Geeks Gor Geeks
Modified String = Geeks For Geeks

Deletion of character in String

To delete any Character in a String, we need:

  • A character that is to deleted in the string (say “ch”)

Below is the implementation of the above approach:

C++
// C++ program to remove a particular character
// from a string.
#include <bits/stdc++.h>
using namespace std;

void removeChar(char* s, char c)
{

    int j, n = strlen(s);
    for (int i = j = 0; i < n; i++)
        if (s[i] != c)
            s[j++] = s[i];

    s[j] = '\0';
}

int main()
{
    char s[] = "geeksforgeeks";
    removeChar(s, 'g');
    cout << s;
    return 0;
}
C
#include <stdio.h>
#include <string.h>

void removeChar(char* s, char c) {
    int i, j, n = strlen(s);
    for (i = j = 0; i < n; i++) {
        if (s[i] != c) {
            s[j++] = s[i];
        }
    }
    s[j] = '\0';
}

int main() {
    char s[] = "geeksforgeeks";
    removeChar(s, 'g');
    printf("%s", s);
    return 0;
}
Java
public class Main {
       // Function to remove a particular character 
      // from a character array
     // Parameters:
    // - s: the character array from which 
    // the character will be removed
    // - c: the character to be removed
    public static void removeChar(char[] s, char c) {
        // Initialize a pointer j to keep track of the 
      // position where characters are being moved
        int j = 0;
        // Loop through the character array
        for (int i = 0; i < s.length; i++) {
            // If the current character is 
           // not the one to be removed
            if (s[i] != c) {
                // Move the character to the 
               // position indicated by j
                s[j++] = s[i];
            }
        }
        // Fill the remaining positions with null characters ('\0')
        while (j < s.length) {
            s[j++] = '\0';
        }
    }

    public static void main(String[] args) {
        // Input string as a character array
        char[] s = "geeksforgeeks".toCharArray();
        // Remove character 'g' from the string
        removeChar(s, 'g');
        // Print the modified string
        System.out.println(s);
    }
}
//This code is added By prachi
Python
# Python program to remove a particular character
# from a string.

def removeChar(s, c):
    # Initialize variables
    n = len(s)
    j = 0
    
    # Iterate through each character of the string
    for i in range(n):
        # If the character is not equal to 
        # the target character, keep it
        if s[i] != c:
            s[j] = s[i]
            j += 1
    
    # Add null character at the end of the modified string
    s = s[:j]
    
    return s

if __name__ == "__main__":
    s = "geeksforgeeks"
# Convert string to list of characters for modification
    s = list(s)  
    s = removeChar(s, 'g')
# Convert list of characters back to string for printing
    print(''.join(s))  
#this code is contributed by Adarsh .
JavaScript
// JavaScript program for the above approach

// Function to remove a particular character from a character array
// Parameters:
// - s: the character array from which the character will be removed
// - c: the character to be removed
function removeChar(s, c) {
    // Initialize a pointer j to keep track of the position where characters are being moved
    let j = 0;
    // Loop through the character array
    for (let i = 0; i < s.length; i++) {
        // If the current character is not the one to be removed
        if (s[i] !== c) {
            // Move the character to the position indicated by j
            s[j++] = s[i];
        }
    }
    // Fill the remaining positions with null characters ('\0')
    while (j < s.length) {
        s[j++] = '\0';
    }
}

// Input string as a character array
let s = "geeksforgeeks".split('');
// Remove character 'g' from the string
removeChar(s, 'g');
// Print the modified string
console.log(s.join(''));

// This code is contributed by Susobhan Akhuli

Output
eeksforeeks

Concatenating strings (combining multiple strings into one).

To concatenate any String to a String, we need:

  • A string that is to appended with the string (say “ch”)

Below is the implementation of the above approach:

C++
// C++ Program for string
// concatenation using '+' operator
#include <iostream>
using namespace std;

// Driver code
int main()
{
    string init("this is init");
    string add(" added now");

    // Appending the string.
    init = init + add;

    cout << init << endl;
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char init[] = "this is init";
    char add[] = " added now";
    char* result = (char*)malloc(strlen(init) + strlen(add) + 1);

    strcpy(result, init);
    strcat(result, add);

    printf("%s\n", result);

    free(result);
    return 0;
}
Java
public class Main {
    public static void main(String[] args) {
        String init = "this is init";
        String add = " added now";

        // Appending the string.
        init = init + add;

        System.out.println(init);
    }
}
Python
def main():
    init = "this is init"
    add = " added now"

    # Concatenate strings
    result = init + add

    # Print the result
    print(result)

# Call the main function
if __name__ == "__main__":
    main()
JavaScript
// Define the main function
function main() {
    let init = "this is init";
    let add = " added now";

    // Appending the string.
    init = init + add;

    console.log(init);
}

// Call the main function
main();

Output
this is init added now

Finding the length/size of a string

To find the length of the String, we need:

  • A string for which the length/size is to be determined (say “str”)

Below is the implementation of the above approach:

C++
// C++ program to find length
// of a string
#include <iostream>
#include <string.h>
using namespace std;

// Driver code
int main()
{
    // String obj
    string str = "GeeksforGeeks";

    // size of string object using size() method
    cout << str.size() << endl;

    return 0;
}
C
#include <stdio.h>
#include <string.h>

int main()
{
    // String
    char str[] = "GeeksforGeeks";

    // Length of string using strlen() function
    int length = strlen(str);

    printf("%d\n", length);

    return 0;
}
Java
public class Main {
    public static void main(String[] args)
    {
        // String object
        String str = "GeeksforGeeks";

        // Size of string object using length() method
        System.out.println(str.length());
    }
}
// This code is contributed by Utkarsh
Python
# Main function
def main():
    # String object
    str = "GeeksforGeeks"

    # Size of string object using len() function
    print(len(str))


# Calling the main function
if __name__ == "__main__":
    main()
JavaScript
// JavaScript program to find length
// of a string

// String
let str = "GeeksforGeeks";

// size of string using length property
console.log(str.length);

Output
13

Comparing Strings for Equality

To compare strings, Define a function to compare values with the following conditions :

  1. if (string1 != string2) it returns a False.
  2. if both the strings are equal lexicographically (string1 == string2), it returns True.

Below is the implementation of the above approach:

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

bool stringCompare(const string& str1, const string& str2) {
    int l1 = str1.length();
    int l2 = str2.length();
    int lmin = min(l1, l2);

    for (int i = 0; i < lmin; i++) {
        int str1_ch = static_cast<int>(str1[i]);
        int str2_ch = static_cast<int>(str2[i]);

        if (str1_ch != str2_ch) {
            return false;
        }
    }

    if (l1 != l2) {
        return false;
    } else {
        return true;
    }
}

int main() {
    string string1 = "Geeksforgeeks";
    string string2 = "Practice";
    string string3 = "Geeks";
    string string4 = "Geeks";

    cout << "Comparing " << string1 << " and " << string2 << " : " 
         << stringCompare(string1, string2) << endl;
    cout << "Comparing " << string3 << " and " << string4 << " : " 
         << stringCompare(string3, string4) << endl;
    cout << "Comparing " << string1 << " and " << string4 << " : " 
         << stringCompare(string1, string4) << endl;

    return 0;
}
C
#include <stdio.h>
#include <stdbool.h>
#include <string.h>

// This function compares two strings lexicographically
bool stringCompare(const char* str1, const char* str2) {
    int l1 = strlen(str1);
    int l2 = strlen(str2);
    int lmin = (l1 < l2) ? l1 : l2;

    for (int i = 0; i < lmin; i++) {
        int str1_ch = (int)str1[i];
        int str2_ch = (int)str2[i];

        if (str1_ch != str2_ch) {
            return false;
        }
    }

    // Edge case for strings with different lengths
    if (l1 != l2) {
        return false;
    }

    // If none of the above conditions is true,
    // it implies both the strings are equal
    return true;
}

// Driver function to test the above program
int main() {
    const char* string1 = "Geeksforgeeks";
    const char* string2 = "Practice";
    const char* string3 = "Geeks";
    const char* string4 = "Geeks";

    // Comparing string1 and string2
    printf("Comparing %s and %s: %s\n", string1, string2, 
            stringCompare(string1, string2) ? "true" : "false");

    // Comparing string3 and string4
    printf("Comparing %s and %s: %s\n", 
            string3, string4, stringCompare(string3, string4) ? 
            "true" : "false");

    // Comparing string1 and string4
    printf("Comparing %s and %s: %s\n", 
            string1, string4, stringCompare(string1, string4) ? 
            "true" : "false");

    return 0;
}
Java
// Java program to Compare two strings
// lexicographically
public class GFG {

    // This method compares two strings
    // lexicographically without using
    // library functions
    public static Boolean stringCompare(String str1,
                                        String str2)
    {

        int l1 = str1.length();
        int l2 = str2.length();
        int lmin = Math.min(l1, l2);

        for (int i = 0; i < lmin; i++) {
            int str1_ch = (int)str1.charAt(i);
            int str2_ch = (int)str2.charAt(i);

            if (str1_ch != str2_ch) {
                return false;
            }
        }

        // Edge case for strings like
        // String 1="Geeks" and String 2="Geeksforgeeks"
        if (l1 != l2) {
            return false;
        }

        // If none of the above conditions is true,
        // it implies both the strings are equal
        else {
            return true;
        }
    }

    // Driver function to test the above program
    public static void main(String args[])
    {
        String string1 = new String("Geeksforgeeks");
        String string2 = new String("Practice");
        String string3 = new String("Geeks");
        String string4 = new String("Geeks");

        // Comparing for String 1 < String 2
        System.out.println(
            "Comparing " + string1 + " and " + string2
            + " : " + stringCompare(string1, string2));

        // Comparing for String 3 = String 4
        System.out.println(
            "Comparing " + string3 + " and " + string4
            + " : " + stringCompare(string3, string4));

        // Comparing for String 1 > String 4
        System.out.println(
            "Comparing " + string1 + " and " + string4
            + " : " + stringCompare(string1, string4));
    }
}
Python
def string_compare(str1, str2):
    l1 = len(str1)
    l2 = len(str2)
    lmin = min(l1, l2)

    for i in range(lmin):
        str1_ch = ord(str1[i])
        str2_ch = ord(str2[i])

        if str1_ch != str2_ch:
            return 0

    if l1 != l2:
        return 0
    else:
        return 1

string1 = "Geeksforgeeks"
string2 = "Practice"
string3 = "Geeks"
string4 = "Geeks"

print("Comparing", string1, "and", string2, ":", 
       string_compare(string1, string2))
print("Comparing", string3, "and", string4, ":", 
       string_compare(string3, string4))
print("Comparing", string1, "and", string4, ":", 
       string_compare(string1, string4))
#this code is contributed by Adarsh.
JavaScript
// Function to compare two strings
function stringCompare(str1, str2) {
    const l1 = str1.length;
    const l2 = str2.length;
    const lmin = Math.min(l1, l2);

    // Iterate over the strings and compare characters
    for (let i = 0; i < lmin; i++) {
        const str1_ch = str1.charCodeAt(i);
        const str2_ch = str2.charCodeAt(i);

        if (str1_ch !== str2_ch) {
            return 0; // If characters don't match, return 0
        }
    }

    // If lengths are not equal, return 0
    if (l1 !== l2) {
        return 0;
    } else {
        return 1; // Otherwise, return 1
    }
}

const string1 = "Geeksforgeeks";
const string2 = "Practice";
const string3 = "Geeks";
const string4 = "Geeks";

console.log("Comparing", string1, "and", 
             string2, ":", stringCompare(string1, string2));
console.log("Comparing", string3, "and", 
             string4, ":", stringCompare(string3, string4));
console.log("Comparing", string1, "and", 
             string4, ":", stringCompare(string1, string4));
// This code is contributed by Utkarsh.

Output
Comparing Geeksforgeeks and Practice : 0
Comparing Geeks and Geeks : 1
Comparing Geeksforgeeks and Geeks : 0


Similar Reads

Implementation of Chinese Remainder theorem (Inverse Modulo based implementation)
We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], ....................... x % num[k-1] = rem[k-1] Example: Input: num[] = {3, 4, 5}, rem[] = {2, 3, 1} Output: 11 Explanation: 11 is the sm
11 min read
Peterson's Algorithm for Mutual Exclusion | Set 1 (Basic C implementation)
Problem: Given 2 processes i and j, you need to write a program that can guarantee mutual exclusion between the two without any additional hardware support. Solution: There can be multiple ways to solve this problem, but most of them require additional hardware support. The simplest and the most popular way to do this is by using Peterson's Algorit
11 min read
Operations of Doubly Linked List with Implementation
A Doubly Linked List (DLL) contains an extra pointer, typically called the previous pointer, together with the next pointer and data which are there in a singly linked list. Below are operations on the given DLL: Add a node at the front of DLL: The new node is always added before the head of the given Linked List. And the newly added node becomes t
15+ min read
Menu driven program in C++ to perform various basic operations on array
Prerequisite: Switch Statement in C/C++, Functions in C/C++, Loops in C and C++, C/C++ do-while loop with Examples Write a menu-driven program to perform below various basic operations in the array: Print all the even values in the array.Print all the odd values in the array.Sum &amp; average of elements in the array.Find the maximum and minimum el
5 min read
Basic Operations for Queue in Data Structure
Basic Operations on Queue: Some of the basic operations for Queue in Data Structure are: enqueue() - Insertion of elements to the queue.dequeue() - Removal of elements from the queue.peek() or front()- Acquires the data element available at the front node of the queue without deleting it.rear() - This operation returns the element at the rear end w
11 min read
Basic Operations on Binary Tree with Implementations
The tree is a hierarchical Data Structure. A binary tree is a tree that has at most two children. The node which is on the left of the Binary Tree is called “Left-Child” and the node which is the right is called “Right-Child”. Also, the smaller tree or the subtree in the left of the root node is called the “Left sub-tree” and that is on the right i
15+ min read
Basic Operations in Stack Data Structure with Implementations
In order to make manipulations in a stack, there are certain operations provided to us for Stack, which include: push() to insert an element into the stackpop() to remove an element from the stacktop() Returns the top element of the stack.isEmpty() returns true if the stack is empty else false.size() returns the size of the stack.In this post, we w
14 min read
Minimum operations required to Sort the Array using following operations
Given an array arr[] of size N. Make the array arr[] sorted in non-decreasing order in the minimum number of operations where you can choose any integer x and replace elements arr[i] == x equal to 0 for, 0 ? i ? N - 1. Examples: Input: n = 3, arr[] = {3, 3, 2}Output: 1Explanation: If you choose x = 3 then after one operation array will become {0, 0
10 min read
Minimum operations to reduce array elements to zero using prefix operations and updates
Given an array arr[] of length N. We can apply 2 types of operations on element of arr[]: Choose a prefix let say arr[0, i] (0 &lt;= i &lt; N) and decrement all elements of prefix by 1. This operation can only apply if all elements in the prefix &gt; 0. Choose an element arr[i] (0 &lt;= i &lt; N) and update it to 0.The task is to output the minimum
8 min read
Minimum number of given operations required to convert a string to another string
Given two strings S and T of equal length. Both strings contain only the characters '0' and '1'. The task is to find the minimum number of operations to convert string S to T. There are 2 types of operations allowed on string S: Swap any two characters of the string.Replace a '0' with a '1' or vice versa. Examples: Input: S = "011", T = "101" Outpu
15 min read
Minimize operations to make one string contain only characters from other string
Given two strings S1 and S2 containing only lower case English alphabets, the task is to minimize the number of operations required to make S1 contain only characters from S2 where in each operation any character of S1 can be converted to any other letter and the cost of the operation will be difference between those two letters. Examples: Input: S
9 min read
Restore original String from given Encrypted String by the given operations
Given a string str and a positive integer N, the task is to reverse N characters and skip N characters until the end of the string to generate the encrypted message. Examples: Input: str = "ihTs suohld ebeas!y", K = 3 Output: This should be easy! Explanation: Reverse "ihT" -&gt; "Thi" "s" remains the same "uoh" -&gt; "hou", and so on. Input: str =
5 min read
Lexicographically smallest string possible by performing K operations on a given string
Given a string S of size N and a positive integer K, the task is to perform atmost K operations on string S to make it lexicographically smallest possible. In one operation, swap S[i] and S[j] and then change S[i] to any character, given 1 ? i &lt; j ? N. Examples: Input: S = "geek", K = 5Output: aaaaExplanation: In 1st operation: take i = 1 and j
8 min read
Minimum operations to convert String A to String B
Given two strings consisting of lowercase alphabets A and B, both of the same length. Each character of both the strings is either a lowercase letter or a question mark '?'. The task is to find the minimum number of operations required to convert A to B, in one operation you can choose an index i, if A[i] is a vowel convert it to a consonant, and i
12 min read
Check if a given string is a valid number (Integer or Floating Point) | SET 1(Basic approach)
Validate if a given string is numeric. Examples: Input : str = "11.5" Output : true Input : str = "abc" Output : false Input : str = "2e10" Output : true Input : 10e5.4 Output : false The following cases need to be handled in the code. Ignore the leading and trailing white spaces.Ignore the '+', '-' and'.' at the start.Ensure that the characters in
11 min read
Count of operations to make a binary string"ab" free
Given a string containing characters 'a' and 'b' only. Convert the given string into a string in which there is no 'ab' substring. To make string 'ab' free we can perform an operation in which we select a 'ab' substring and replace it by 'bba'. Find the total number of operations required to convert the given string. Examples: Input : s = 'abbaa' O
5 min read
Converting one string to other using append and delete last operations
Given an integer k and two strings str1 and str2 determine whether or not we can convert str1 to str2 by performing exactly k of the below operations on str1. Append a lowercase English alphabetic letter to the end of the str1. Delete the last character in str1 (Performing this operation on an empty string results in an empty string) Examples: Inpu
7 min read
Final string after performing given operations
Given a string str containing only characters x and y, the task is to perform the following operations while possible: Find an index such that s[i] = 'x' and s[i+1] = 'y' and delete both the characters s[i] and s[i+1], if no such index is found then find an index such that s[i] = 'y' and s[i+1] = 'x' and swap(s[i], s[i+1]). Print the final string a
6 min read
Form N-copy string with add, remove and append operations
A string is called a N-copy string when it is formed by N copies of letter 'G'. ie "GGGG" is a 4-copy string since it contains 4 copies of the letter 'G'. Initially we have a empty string on which we can perform the following three operations: Add a single letter 'G' with a cost of X.Remove a single letter 'G' with a cost of X.Append the string for
9 min read
Operations required to make the string empty
Given a string str, the task is to make the string empty with the given operation. In a single operation, you can pick some characters of the string (each of the picked characters should have the same frequency) and remove them from the string. Print the total operations required to make the string empty. Examples: Input: str = "aabbccc" Output: 2
5 min read
Count Fair pairs in a String with Uppercase-Lowercase operations
Given a string S of length N that contains only uppercase and lowercase letters, the task is to find the maximum number of pairs that consist of an uppercase and a lowercase version of the same letter, and each character can only belong to one pair. You are allowed to perform K operations, wherein each operation, you can either change an uppercase
9 min read
Minimum number of operations on a binary string such that it gives 10^A as remainder when divided by 10^B
Given a binary string str of length N and two integers A and B such that 0 ? A &lt; B &lt; n. The task is to count the minimum number of operations on the string such that it gives 10A as remainder when divided by 10B. An operation means changing 1 to 0 or 0 to 1. Examples: Input: str = "1001011001", A = 3, B = 6 Output: 2 The string after 2 operat
5 min read
Encrypt the given string with the following operations
Given a string s, the task is to encrypt the string in the following way: If the frequency of current character is even, then increment current character by x.If the frequency of current character is odd, then decrement current character by x. Note: All the operations are circular that is adding 1 to 'z' will give 'a' and subtracting 1 from 'a' wil
6 min read
Maximum number of given operations to remove the entire string
Given string str containing lowercase English characters, we can perform the following two operations on the given string: Remove the entire string.Remove a prefix of the string str[0...i] only if it is equal to the sub-string str[(i + 1)...(2 * i + 1)]. The task is to find the maximum number of operations required to delete the entire string. Exam
11 min read
Minimum operations required to convert a binary string to all 0s or all 1s
Given a binary string str, the task is to find the minimum number of operations required to make all the characters of the string same i.e. either the resultant string contains all 0s or all 1s. In a single operation, any block of consecutive 0s can be converted to a block of consecutive 1s of the same length and vice versa. Examples: Input: str =
4 min read
Minimum given operations required to convert a given binary string to all 1's
Given a binary number as a string str of length L. The task is to find the minimum number of operations needed so that the number becomes 2L-1, that is a string consisting of only 1's of the length L. In each operation, the number N can be replaced by N xor (N + 1). Examples: Input: str = "10010111" Output: 5 N = 10010111, N + 1 = 10011000, so N xo
7 min read
Minimum operations required to make the string satisfy the given condition
Given a string str, the task is to make the string start and end at the same character with the minimum number of given operations. In a single operation, any character of the string can be removed. Note that the length of the resultant string must be greater than 1 and it is not possible then print -1. Examples: Input: str = "geeksforgeeks" Output
7 min read
Minimum number of operations required to obtain a given Binary String
Given a binary strings S of length N, the task is to obtain S from a string, say T, of length N consisting only of zeroes, by minimum number of operations. Each operation involves choosing any index i from string S and flipping all the bits at indices [i, N - 1] of the string T. Examples: Input: S = "101" Output: 3 Explanation: "000" -&gt; "111" -
8 min read
Lexicographically smallest string after M operations
Given a string S and integer M. The task is to perform exactly M operations to get lexicographical smallest string. In each operation, select one character optimally from the string and update it with immediate next character ( aaa -&gt; aab ), so that string remain lexicographical smallest.Multiple operations are allowed over single character of t
7 min read
Minimum number of operations required to maximize the Binary String
Given a binary string S, the task is to find the minimum number of swaps required to be performed to maximize the value represented by S. Examples: Input: S = "1010001" Output: 1 Explanation: Swapping S[2] and S[7], modifies the string to 1110000, thus, maximizing the number that can be generated from the string.Input: S = "110001001" Output: 2 Exp
7 min read
Article Tags :
Practice Tags :