Open In App

Insert a character in String at a Given Position

Last Updated : 06 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string s, a character c and an integer position pos, the task is to insert the character c into the string s at the specified position pos.

Examples:

Input: s = "Geeks", c = 'A', pos = 3
Output: GeeAks

Input: s = "HelloWorld", c = '!', pos = 5
Output: Hello!World

[Approach-1] Using Built-In Methods

We will use library methods like string insert in C++, StringBuilder insert in Java and String Slicing in Python.

C++
// C++ program to insert a character at specific
// position using Built in functions
  
#include <bits/stdc++.h>
using namespace std;

string insertChar(string &s, char c, int pos) {
  
    // Insert character at specified position
    s.insert(s.begin() + pos, c);
  	return s;
}

int main() {
    string s = "Geeks";
    cout << insertChar(s, 'A', 3);
    return 0;
}
Java
// Java program to insert a character at specific
// position using Built in functions

class GfG {
    static String insertChar(StringBuilder sb, char c, int pos) {
      
        // Insert character at specified position
        sb.insert(pos, c);
        return sb.toString();
    }

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Geeks");
        System.out.println(insertChar(sb, 'A', 3));
    }
}
Python
# Python program to insert a character at specific
# position using Built in functions

def insertChar(s, c, pos):
  
    # Insert character at specified position
    return s[:pos] + c + s[pos:]

s = "Geeks"
print(insertChar(s, 'A', 3)) 
C#
// C# program to insert a character at specific
// position using Built in functions

using System;

class GfG {
    static string insertChar(string s, char c, int pos) {
      
        // Insert character at specified position
        return s.Substring(0, pos) + c + s.Substring(pos);
    }

    static void Main() {
        string s = "Geeks";
        Console.WriteLine(insertChar(s, 'A', 3));
    }
}
JavaScript
// JavaScript program to insert a character at 
// specific position using Built in functions

function insertChar(s, c, pos) {

    // Insert character at specified position
    return s.slice(0, pos) + c + s.slice(pos);
}

const s = "Geeks";
console.log(insertChar(s, 'A', 3));

Output
GeeAks

Time Complexity: O(n) where n is the length of the string.

[Approch-2] Using Custom Method

First, iterate through the given string, inserting all the characters into a new string until we reach the position where the given character needs to be inserted. At that position, insert the character, and then append the remaining characters from the input string to the new string.

C++
// C++ program to insert a character at specific
// position using custom method

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

string insertChar(string &s, char c, int pos) {
    string res = "";
    for (int i = 0; i < s.length(); i++) {
      
        // Insert the character at 
      	// the given position
        if (i == pos)
            res.push_back(c);
      
        // Insert the original characters
        res.push_back(s[i]);
    }
  
    // If the given pos is beyond the length,  
    // append the character at the end
    if (pos >= s.length()) 
        res.push_back(c);
      
    return res;
}

int main() {
    string s = "Geeks";
    cout << insertChar(s, 'A', 3);
    return 0;
}
C
// C program to insert a character at specific
// position using custom method

#include <stdio.h>
#include <string.h>

void insertChar(char *s, char c, int pos, char *res) {
    int length = strlen(s);
    int j = 0;
    
    for (int i = 0; i < length; i++) {
      
        // Insert the character at the given position
        if (i == pos) 
            res[j++] = c;
        
        // Insert the original characters
        res[j++] = s[i];
    }

    // If the given pos is beyond the length,
    // append the character at the end
    if (pos >= length) 
        res[j++] = c;

    res[j] = '\0'; 
}

int main() {
    char s[] = "Geeks";
  	int len = strlen(s);
    char res[len + 1]; 
    insertChar(s, 'A', 3, res); 
    printf("%s\n", res); 
    return 0;
}
Java
// Java program to insert a character at specific
// position using custom method

class GfG {
    static String insertChar(String s, char c, int pos) {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
      
            // Insert the character at the given position
            if (i == pos) 
                res.append(c);
      
            // Insert the original characters
            res.append(s.charAt(i));
        }
  
        // If the given pos is beyond the length,  
        // append the character at the end
        if (pos >= s.length()) 
            res.append(c);
      
        return res.toString();
    }

    public static void main(String[] args) {
        String s = "Geeks";
        System.out.println(insertChar(s, 'A', 3));
    }
}
Python
# Python program to insert a character at 
# specific position using custom method

def insertChar(s, c, pos):
    res = ""
    for i in range(len(s)):
      
        # Insert the character at 
        # the given position
        if i == pos: 
            res += c
      
        # Insert the original characters
        res += s[i]
  
    # If the given pos is beyond the length,  
    # append the character at the end
    if pos >= len(s): 
        res += c
      
    return res

s = "Geeks"
print(insertChar(s, 'A', 3))
C#
// C# program to insert a character at specific position
// using custom method

using System;

class GfG {
    static string insertChar(string s, char c, int pos) {
        string res = "";
        for (int i = 0; i < s.Length; i++) {
      
            // Insert the character at 
            // the given position
            if (i == pos) 
                res += c;
      
            // Insert the original characters
            res += s[i];
        }
  
        // If the given pos is beyond the length,  
        // append the character at the end
        if (pos >= s.Length) 
            res += c;
      
        return res;
    }

    static void Main() {
        string s = "Geeks";
        Console.WriteLine(insertChar(s, 'A', 3));
    }
}
JavaScript
// JavaScript program to insert a character at 
// specific position using custom method

function insertChar(s, c, pos) {
    let res = "";
    for (let i = 0; i < s.length; i++) {
      
        // Insert the character at 
        // the given position
        if (i === pos) 
            res += c;
      
        // Insert the original characters
        res += s[i];
    }
  
    // If the given pos is beyond the length,  
    // append the character at the end
    if (pos >= s.length) 
        res += c;
      
    return res;
}

let s = "Geeks";
console.log(insertChar(s, 'A', 3));

Output
GeeAks

Time Complexity: O(n) where n is the length of the string.


Next Article
Article Tags :
Practice Tags :

Similar Reads