Open In App
Related Articles

Basic String Operations with Implementation

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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);
    }
}

                    

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();

                    

Python3

# 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

                    

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);
    }
}

                    

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);
    }
}

                    

Python3

# 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()

                    

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

                    

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;
}

                    

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;
}

                    

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));
    }
}

                    

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








Last Updated : 29 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads