Open In App

Basic String Operations with Implementation

Last Updated : 07 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

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 “s”)
  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 = s[k];
OR
char ch = s.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 &s, int k)
{

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

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

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

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

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

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

    // Driver code
    public static void main(String[] args) {
        String s = "GeeksforGeeks ";
        int k = 4;
        System.out.println(accessCharByIndex(s, 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
if __name__ == "__main__":
    s = "GeeksforGeeks "
    k = 4
    print(access_char_by_index(s, k))
C#
using System;

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

    static void Main()
    {
        string s = "GeeksforGeeks ";
        int k = 4;
        Console.WriteLine(AccessCharByIndex(s, k));
    }
}
JavaScript
// Function to demonstrate access by index
function accessCharByIndex(s, k) {

    // Return the character at the kth index in the string str
    return s[k];
}

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

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 &s, string ch, int k)
{

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

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

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

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

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

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

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

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

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

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

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

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

    // Function to demonstrate insert
    public static void insertDemo(String s, String ch, int k) {
      
        // Inserts ch at kth index of str
        StringBuilder sb = new StringBuilder(s);
        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__":
    s = "GeeksGeeks "
    ch_to_insert = "for"
    index_to_insert = 5

    print("Original String:", s)
    insert_demo(s, ch_to_insert, index_to_insert)
C#
using System;

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

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

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

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

// Call the main function
let s = "GeeksGeeks ";
let ch = "for";
let k = 5;

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

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>

using namespace std;

int main() 
{
    string s = "Geeks Gor Geeks";
    int index = 6;
    char ch = 'F';

    cout << "Original String = " << s << endl;

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

    cout << "Modified String = " << s << endl;

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

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

    // Define the index
    int index = 6;

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

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

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

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

    return 0;
}
Java
public class GFG {

    public static void main(String args[])
    {

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

        // Get the index
        int index = 6;

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

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

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

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

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

    # Replace character at the specified index
    lst[index] = ch

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



# Entry point of the program
if __name__ == "__main__":
  
    # Original string
    s = "Geeks Gor Geeks"

    # Index to replace character
    index = 6

    # New character
    ch = 'F'

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

    # Replace character at the specified index
    s = replace_ch(s, index, ch)

    # Print modified string
    print("Modified String =", s)
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++
#include <iostream>
using namespace std;

void removeChar(string &s, char c) 
{
    int j = 0;
    for (int i = 0; i < s.size(); i++) {
        if (s[i] != c) {
          
            // Move other characters 
            s[j++] = s[i];  
        }
    }
  
    // j is new size of the string
    s.resize(j); 
}

int main() 
{
    string s = "geeksforgeeks";
    removeChar(s, 'g');
    cout << s;  // Output the modified string
    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 GfG {

    // Function to remove a particular character
    // from a StringBuilder
    // Parameters:
    // - s: the StringBuilder from which
    // the character will be removed
    // - c: the character to be removed
    public static void removeChar(StringBuilder s, char c) {
        int j = 0;
      
        // Loop through the StringBuilder
        for (int i = 0; i < s.length(); i++) {
          
            // If the current character is not the one to be removed
            if (s.charAt(i) != c) {
              
                // Move the character to the position indicated by j
                s.setCharAt(j++, s.charAt(i));
            }
        }
        // Delete the remaining characters
        s.delete(j, s.length());
    }

    public static void main(String[] args) {
      
        // Input string as a StringBuilder
        StringBuilder s = new StringBuilder("geeksforgeeks");

        // Remove character 'g' from the string
        removeChar(s, 'g');

        // Print the modified string
        System.out.println(s);
    }
}
Python
def removeChar(s, c):
  
    # Use list comprehension to filter 
    # out the target character
    return ''.join([ch for ch in s if ch != c])

if __name__ == "__main__":
    s = "geeksforgeeks"
    s = removeChar(s, 'g')
    print(s)
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

C++
// CPP code perform relational
// operation using compare function
#include <iostream>

using namespace std;

void compareFunction(string &s1, string &s2)
{
	// comparing both using inbuilt function
	int x = s1.compare(s2);

	if (x != 0) {
		cout << s1 << " is not equal to "
			<< s2 << endl;
		if (x > 0)
			cout << s1 << " is greater than "
				<< s2 << endl;
		else
			cout << s2 	<< " is greater than "
				<< s1 << endl;
	}
	else
		cout << s1 << " is equal to " << s2 << endl;
}

// Driver Code
int main()
{
	string s1("geeks");
	string s2("forGeeks");
	compareFunction(s1, s2);
	string s3("geeks");
	string s4("geeks");
	compareFunction(s3, s4);
	return 0;
}
C
#include <stdio.h>
#include <string.h>

void compareStrings(char *s1, char *s2) {
    // comparing both using inbuilt function
    int x = strcmp(s1, s2);

    if (x != 0) {
        printf("%s is not equal to %s\n", s1, s2);
        if (x > 0) {
            printf("%s is greater than %s\n", s1, s2);
        } else {
            printf("%s is greater than %s\n", s2, s1);
        }
    } else {
        printf("%s is equal to %s\n", s1, s2);
    }
}

int main() {
    compareStrings("geeks", "forGeeks");
    compareStrings("geeks", "geeks");
    return 0;
}
Java
public class RelationalOps {
    public static void compareStrings(String s1, String s2) {
        // comparing both using inbuilt function
        int x = s1.compareTo(s2);

        if (x != 0) {
            System.out.println(s1 + " is not equal to " + s2);
            if (x > 0) {
                System.out.println(s1 + " is greater than " + s2);
            } else {
                System.out.println(s2 + " is greater than " + s1);
            }
        } else {
            System.out.println(s1 + " is equal to " + s2);
        }
    }

    public static void main(String[] args) {
        compareStrings("geeks", "forGeeks");
        compareStrings("geeks", "geeks");
    }
}
Python
def compare_strings(s1, s2):
    # comparing both using inbuilt comparison
    if s1 != s2:
        print("s1 is not equal to s2")
        if s1 > s2:
            print("s1 is greater than s2")
        else:
            print("s2 is greater than s1")
    else:
        print("s1 is equal to s2")

# Driver code
compare_strings("geeks", "forGeeks")
compare_strings("geeks", "geeks")
JavaScript
function compareStrings(s1, s2) {
    // comparing both using inbuilt comparison
    if (s1 !== s2) {
        console.log(`${s1} is not equal to ${s2}`);
        if (s1 > s2) {
            console.log(`${s1} is greater than ${s2}`);
        } else {
            console.log(`${s2} is greater than ${s1}`);
        }
    } else {
        console.log(`${s1} is equal to ${s2}`);
    }
}

// Driver code
compareStrings("geeks", "forGeeks");
compareStrings("geeks", "geeks");


Next Article
Article Tags :
Practice Tags :

Similar Reads