The Wayback Machine - https://web.archive.org/web/20240827150430/https://www.geeksforgeeks.org/how-to-insert-characters-in-a-string-at-a-certain-position/
Open In App

How to insert characters in a string at a certain position?

Last Updated : 21 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Medium
31.11%
11.4K

Given a string str and an array of indices chars[] that describes the indices in the original string where the characters will be added. For this post, let the character to be inserted in star (*). Each star should be inserted before the character at the given index. Return the modified string after the stars have been added.

Examples:

Input: str = “geeksforgeeks”, chars = [1, 5, 7, 9]
Output: g*eeks*fo*rg*eeks
Explanation: The indices 1, 5, 7, and 9 correspond to the bold characters in “geeksforgeeks”.

Input: str = “spacing”, chars = [0, 1, 2, 3, 4, 5, 6]
Output: “*s*p*a*c*i*n*g”

Approach: To solve the problem follow the below idea:

Iterate over the string and keep track of the count of the characters in the string so far and whenever your count becomes equal to the element in the array of stars, append a star to the resultant string and move ahead in your star array.

Follow the steps mentioned below to implement the idea:

  • Create a string ans for storing your resultant string.
  • Take one pointer j initially as 0.
  • Iterate over the string and whenever your index that represents the count of characters becomes equal to the element in stars[j], append the star in your ans string and move the j pointer ahead.
  • Also, at each move, append the current character in your string ans.

Below is the implementation of the above approach:

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to add stars
string addStars(string s, vector<int>& stars)
{
 
    // Create a string ans for storing
    // resultant string
    string ans = "";
 
    int j = 0;
 
    for (int i = 0; i < s.length(); i++) {
 
        // If the count of characters
        // become equal to the stars[j],
        // append star
        if (j < stars.size() && i == stars[j]) {
            ans += '*';
            j++;
        }
        ans += s[i];
    }
 
    return ans;
}
 
// Driver code
int main()
{
    string str = "geeksforgeeks";
    vector<int> chars = { 1, 5, 7, 9 };
    string ans = addStars(str, chars);
 
    // Printing the resultant string
    cout << ans << endl;
}


Java




// Java code to implement the approach
import java.io.*;
 
class GFG
{
 
  // Function to add stars
  public static String addStars(String s, int stars[])
  {
 
    // Create a string ans for storing
    // resultant string
    String ans = "";
 
    int j = 0;
 
    for (int i = 0; i < s.length(); i++) {
 
      // If the count of characters
      // become equal to the stars[j],
      // append star
      if (j < stars.length && i == stars[j]) {
        ans += '*';
        j++;
      }
      ans += s.charAt(i);
    }
 
    return ans;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    String str = "geeksforgeeks";
    int chars[] = { 1, 5, 7, 9 };
    String ans = addStars(str, chars);
 
    // Printing the resultant string
    System.out.println(ans);
  }
}
 
// This code is contributed by Rohit Pradhan


Python3




# Python3 code to implement the above approach
 
# Function to add stars
def addStars(s, stars) :
 
    # Create a string ans for storing
    # resultant string
    ans = "";
    j = 0;
 
    for i in range(len(s)) :
 
        # If the count of characters
        # become equal to the stars[j],
        # append star
        if (j < len(stars) and i == stars[j]) :
            ans += '*';
            j += 1;
        ans += s[i];
    return ans;
 
# Driver code
if __name__ == "__main__" :
    string = "geeksforgeeks";
    chars = [ 1, 5, 7, 9 ];
    ans = addStars(string, chars);
 
    # Printing the resultant string
    print(ans);
     
    # This code is contributed by AnkThon


C#




// C# code to implement the approach
using System;
using System.Collections;
 
public class GFG
{
   
  // Function to add stars
  public static string addStars(string s, int[] stars)
  {
 
    // Create a string ans for storing
    // resultant string
    string ans = "";
 
    int j = 0;
 
    for (int i = 0; i < s.Length; i++) {
 
      // If the count of characters
      // become equal to the stars[j],
      // append star
      if (j < stars.Length && i == stars[j]) {
        ans += '*';
        j++;
      }
      ans += s[i];
    }
 
    return ans;
  }
 
  // Driver code
  public static void Main(string[] args)
  {
    string str = "geeksforgeeks";
    int[] chars = { 1, 5, 7, 9 };
    string ans = addStars(str, chars);
 
    // Printing the resultant string
    Console.Write(ans);
  }
}
 
// This code is contributed by garg28harsh.


Javascript




// Javascript code to implement the approach
 
// Function to add stars
function addStars(s, stars) {
 
    // Create a string ans for storing
    // resultant string
    let ans = "";
 
    let j = 0;
 
    for (let i = 0; i < s.length; i++) {
 
        // If the count of characters
        // become equal to the stars[j],
        // append star
        if (j < stars.length && i == stars[j]) {
            ans += '*';
            j++;
        }
        ans += s[i];
    }
 
    return ans;
}
 
// Driver code
 
let str = "geeksforgeeks";
let chars = [1, 5, 7, 9];
let ans = addStars(str, chars);
 
// Printing the resultant string
console.log(ans)
 
// This code is contributed by Saurabh Jaiswal


Output

g*eeks*fo*rg*eeks




Time Complexity: O(N)
Auxiliary Space: O(N)

Approach: using inbuilt insert function.

In this approach we need to increase the length of orignal string as on insert operation the orignal string get modified and so the target index needs to be increased by 1 so we used k.

The addStars function inserts an asterisk (*) at the positions specified in the chars vector. Here’s step by step approach for same:

  1. The addStars function takes a string s and a vector of integers stars as input.
  2. It iterates through the stars vector using a for loop.
  3. For each position specified in the stars vector, it inserts an asterisk (*) at that position in the string s(using insert function).
  4. we increment the k on insertion because size increases on an insertion operation.
  5. The updated string is returned.

C++




#include <iostream>
#include <vector>
#include <string>
using namespace std;
 
// Function to add stars
string addStars(string s, vector<int>& stars)
{
    // Iterate through the vector of positions
    int k=0;
    for (int i = 0; i < stars.size(); i++) {
        // Insert a star at the specified position
        s.insert(stars[i]+ k++, "*");
    }
    return s;
}
 
// Driver code
int main()
{
    string str = "geeksforgeeks";
    vector<int> chars = { 1, 5, 7, 9 };
    string ans = addStars(str, chars);
 
    // Printing the resultant string
    cout << ans << endl;
}


Java




import java.util.ArrayList;
import java.util.List;
 
public class GFG {
   
  // Function to add stars
    public static String addStars(String s, List<Integer> stars) {
        // Iterate through the vector of positions
          int k = 0;
        for (int i = 0; i < stars.size(); i++) {
            // Insert a star at the specified position
              s = s.substring(0, stars.get(i) + k) + "*" + s.substring(stars.get(i) + k);
            k++;
        }
          // Return result
        return s;
    }
 
    public static void main(String[] args) {
        // Test case
          String str = "geeksforgeeks";
        List<Integer> chars = new ArrayList<>();
        chars.add(1);
        chars.add(5);
        chars.add(7);
        chars.add(9);
        String ans = addStars(str, chars);
        System.out.println(ans);
    }
}


Python3




# Function to add stars
def addStars(s, stars):
   
    # Iterate through the vector of positions
    k = 0
    for i in range(len(stars)):
       
        # Insert a star at the specified position
        s = s[:stars[i]+k] + "*" + s[stars[i]+k:]
        k += 1
    return s
 
 
# Driver code
str = "geeksforgeeks"
chars = [1, 5, 7, 9]
ans = addStars(str, chars)
 
# Printing the resultant string
print(ans)


C#




using System;
using System.Collections.Generic;
 
namespace CodeTranslation
{
    class Program
    {
        // Function to add stars
        static string AddStars(string s, List<int> stars)
        {
            // Iterate through the list of positions
            int k = 0;
            for (int i = 0; i < stars.Count; i++)
            {
                // Insert a star at the specified position
                s = s.Insert(stars[i] + k++, "*");
            }
            return s;
        }
 
        // Driver code
        static void Main(string[] args)
        {
            string str = "geeksforgeeks";
            List<int> chars = new List<int> { 1, 5, 7, 9 };
            string ans = AddStars(str, chars);
            // Printing the resultant string
            Console.WriteLine(ans);
        }
    }
}


Javascript




// Function to add stars
function addStars(s, stars) {
    // Iterate through the vector of positions
    let k = 0;
    for (let i = 0; i < stars.length; i++) {
        // Insert a star at the specified position
        s = s.slice(0, stars[i] + k) + "*" + s.slice(stars[i] + k);
        k += 1;
    }
     
    // Return result
    return s;
}
 
// Test case
let str = "geeksforgeeks";
let chars = [1, 5, 7, 9];
let ans = addStars(str, chars);
 
console.log(ans);


Output

g*eeks*fo*rg*eeks




Time Complexity: O(N*K)
Auxiliary Space: O(N)

Explaination:
The time complexity of this approach is O(n*k), where n is the length of the string and k is the size of the vector. This is because for each position in the vector, we need to insert an asterisk into the string, which takes O(n) time.

The auxiliary space complexity is O(1), as we are not using any additional data structures.



Previous Article
Next Article

Similar Reads

Insert a whole linked list into other at k-th position
Given two linked lists and a number k. Insert second linked list in to first at k-th position Examples: Input : a : 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL b : 7-&gt;8-&gt;9-&gt;10-&gt;11-&gt;NULL k = 2 Output :1-&gt;2-&gt;7-&gt;8-&gt;9-&gt;10-&gt;11-&gt;3-&gt;4-&gt;5-&gt;NULL Input : a: 10-&gt;15-&gt;20-&gt;NULL b: 11-&gt;17-&gt;16-&gt;18-&gt;NULL k =
10 min read
How to insert a Node in a Singly Linked List at a given Position using Recursion
Given a singly linked list as list, a position, and a node, the task is to insert that element in the given linked list at a given position using recursion. Examples: Input: list = 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7, node = (val=100,next=null), position = 4 Output: 1-&gt;2-&gt;3-&gt;100-&gt;4-&gt;5-&gt;6-&gt;7Explanation: Here the node with valu
14 min read
Search insert position of K in a sorted array
Given a sorted array arr[] consisting of N distinct integers and an integer K, the task is to find the index of K, if it's present in the array arr[]. Otherwise, find the index where K must be inserted to keep the array sorted. Examples: Input: arr[] = {1, 3, 5, 6}, K = 5Output: 2Explanation: Since 5 is found at index 2 as arr[2] = 5, the output is
9 min read
XOR Linked List - Insert an element at a specific position
Given a XOR linked list and two integers position and value, the task is to insert a node containing value as the positionth node of the XOR Linked List. Examples: Input: 4&lt;--&gt;7&lt;--&gt;9&lt;--&gt;7, position = 3, value = 6 Output: 4&lt;--&gt;7&lt;--&gt;6&lt;--&gt;9&lt;--&gt;7Explanation: Inserting a node at the 3rd position with value 6 mod
15+ min read
Insert a node at a specific position in a linked list
Given a singly linked list, a position and an element, the task is to write a program to insert that element in a linked list at a given position.  Examples:  Input: 3-&gt;5-&gt;8-&gt;10, data = 2, position = 2Output: 3-&gt;2-&gt;5-&gt;8-&gt;10 Input: 3-&gt;5-&gt;8-&gt;10, data = 11, position = 5Output: 3-&gt;5-&gt;8-&gt;10-&gt;11  Approach: To ins
10 min read
Insert a Node at a specific position in Doubly Linked List
Given a Doubly Linked List, the task is to insert a new node at a specific position in the linked list.  Examples: Input: Linked List = 1 &lt;-&gt; 2 &lt;-&gt; 4, newData = 3, position = 3Output: Linked List = 1 &lt;-&gt; 2 &lt;-&gt; 3 &lt;-&gt; 4Explanation: New node with data = 3 is inserted at position 3 Input: Linked List = 2 &lt;-&gt; 3, newDa
13 min read
Number of ways to insert two pairs of parentheses into a string of N characters
Given a string str of length N, the task is to find the number of ways to insert only 2 pairs of parentheses into the given string such that the resultant string is still valid.Examples: Input: str = "ab" Output: 6 ((a))b, ((a)b), ((ab)), (a)(b), (a(b)), a((b)) which are a total of 6 ways.Input: str = "aab" Output: 20 Approach: it can be observed t
3 min read
Difference between sums of odd position and even position nodes for each level of a Binary Tree
Given a Binary Tree, the task is to find the absolute difference between the sums of odd and even positioned nodes. A node is said to be odd and even positioned if its position in the current level is odd and even respectively. Note that the first element of each row is considered as odd positioned.Examples: Input: 5 / \ 2 6 / \ \ 1 4 8 / / \ 3 7 9
8 min read
Count N-digit numbers such that every position is divisible by the digit at that position
Given a positive integer N, the task is to count the number of N-digit numbers such that every index (1-based indexing) in the number is divisible by the digit occurring at that index. Since the court can be very large, print it modulo 109 + 7. Examples: Input: N = 2Output: 2Explanation: The numbers 11 and 12 are the only 2-digit numbers satisfying
6 min read
Transform string A into B by deleting characters from ends and reinserting at any position
Given two strings A and B that are anagrams of each other, the task is to convert A to B if possible in minimum number of operations. An operation is defined as removing either the first or the last character in A and inserting it back anywhere in the string. Examples: Input: A = "edacb", B = "abcde"Output : 3Explanation : The three operations are:
13 min read
Modify characters of a string by adding integer values of same-indexed characters from another given string
Given two strings S and N of the same length, consisting of alphabetical and numeric characters respectively, the task is to generate a new string obtained by adding the integer value of each character of string N with the ASCII value of the same indexed character of string S. Finally, print the resultant string.Note: If the sum exceeds 122, then s
6 min read
Longest Common Subsequence (LCS) by repeatedly swapping characters of a string with characters of another string
Given two strings A and B of lengths N and M respectively, the task is to find the length of the longest common subsequence that can be two strings if any character from string A can be swapped with any other character from B any number of times. Examples: Input: A = "abdeff", B = "abbet"Output: 4Explanation: Swapping A[5] and B[4] modifies A to "a
7 min read
Check if a string can be made palindromic by swapping pairs of characters from indices having unequal characters in a Binary String
Given a string S and a binary string B, both of length N, the task is to check if the given string S can be made palindromic by repeatedly swapping characters at any pair of indices consisting of unequal characters in the string B. Examples: Input: S = "BAA", B = "100"Output: YesExplanation:Swapping S[0] and S[1] modifies S to "ABA" and B to "010".
15+ min read
Maximum Subarray Sum Excluding Certain Elements
Given an array of A of n integers and an array B of m integers find the Maximum Contiguous Subarray Sum of array A such that any element of array B is not present in that subarray. Examples : Input : A = {1, 7, -10, 6, 2}, B = {5, 6, 7, 1} Output : 2 Explanation Since the Maximum Sum Subarray of A is not allowed to have any element that is present
15+ min read
Number of array elements derivable from D after performing certain operations
Given an array of N integers and 3 integers D, A and B. The task is to find the number of array elements that we can convert D into by performing the following operations on D: Add A (+A)Subtract A (-A)Add B (+B)Subtract B (-B) Note: It is allowed to perform any number of operations of any type. Examples: Input : arr = {1, 2, 3}, D = 6, A = 3, B =
10 min read
Count number of step required to reduce N to 1 by following certain rule
Given a positive integer [Tex]N [/Tex]. Find the number of steps required to minimize it to 1. In a single step N either got reduced to half if it is power of 2 else N is reduced to difference of N and its nearest power of 2 which is smaller than N. Examples: Input : N = 2 Output : 1Input : N = 20 Output : 3 Simple Approach: As per question a very
4 min read
Distribute the white and black objects into maximum groups under certain constraints
Given W white objects and B black objects and a number D, the task is to find if it is possible to distribute the white and black objects into the maximum number of groups such that each group contains at least one of each type of object and the difference between the number of objects of different types in each group does not exceed D. Examples: I
4 min read
Biggest number by arranging numbers in certain order
Given an array of n numbers. Arrange them in a way that yields the largest value. While arranging the order of even numbers with respect to each other and the order of odd numbers with respect to each other should be maintained respectively. Examples: Input : {78, 81, 88, 79, 117, 56} Output : 8179788856117 The numbers are arranged in the order: 81
8 min read
Sort array by performing swapping under certain condition
Given an array of positive elements arr[] of size N. You can select any index i such that i + 1 &lt; N and swap arr[i], arr[i + 1] if they have the same number of set bits in their binary representation. The task is to determine whether it is possible to sort the array in ascending order by swapping any number of times. If it is possible, you shoul
7 min read
How to Insert Symbols and Special Characters in Microsoft Word?
Microsoft Word is a software tool that allows us to create documents file like articles, office letters, projects files and many more in a very simplest and easy manner. MS Word makes our document more attractive as compared to paper or file work by providing different features like it has different sizes of pages, fonts, colors, design, bullets, t
4 min read
Minimum time to write characters using insert, delete and copy operation
We need to write N same characters on a screen and each time we can insert a character, delete the last character and copy and paste all written characters i.e. after copy operation count of total written character will become twice. Now we are given time for insertion, deletion and copying. We need to output minimum time to write N characters on t
8 min read
Count characters at same position as in English alphabet
Given a string of lower and uppercase characters, the task is to find how many characters are in the same position as in the English alphabet. Examples: Input: ABcED Output : 3 First three characters are at same position as in English alphabets. Input: geeksforgeeks Output : 1 Only 'f' is at same position as in English alphabet Input : alphabetical
7 min read
Minimize deletions such that sum of position of characters is at most K
Given a string S consisting of lower case letters and an integer K, the task is to remove minimum number of letters from the string, such that the sum of alphabetic ordering of the letters present in the string is at most K. Examples : Input: S = "abca", K = 2Output: "aa"Explanation: Initial sum for the given string is 1 + 2 + 3 + 1 = 7 (since posi
8 min read
Permutation of a string with maximum number of characters greater than its adjacent characters
Given a string str, the task is to print the maximum count of characters which are greater than both its left and right character in any permutation of the string. Examples: Input: str = "abc" Output: 1 Permutations of the string with the count of maximal character in each string are: abc - 0 acb - 1 Here a &lt; c &gt; b bac - 0 bca - 1 Here b &lt;
11 min read
Rearrange the characters of the string such that no two adjacent characters are consecutive English alphabets
Given string str of size N consists of lower-case English alphabets. The task is to find the arrangement of the characters of the string such that no two adjacent characters are neighbors in English alphabets. In case of multiple answers print any of them. If no such arrangement is possible then print -1.Examples: Input: str = "aabcd" Output: bdaac
6 min read
Count of ungrouped characters after dividing a string into K groups of distinct characters
Given a lower alphabetic string "S" of size N, and an integer K; the task is to find the count of characters that will remain ungrouped, after dividing the given string into K groups of distinct characters.Examples: Input: S = "stayinghomesaveslife", K = 1 Output: 6 Explanation: In the string S the elements whose occurrence is more than one time ar
6 min read
Make String repeating after every K characters by replacing characters at missing place
Given an string S and integer K and there are also some missing character i.e. ( _ ), the task is make the string S repeating after every K characters by replacing the appropriate character at missing place i.e. ( _ ). If it is not possible then print -1. Note: If there are multiple possible strings, then print the smallest lexicographically string
7 min read
Minimum cost to remove the spaces between characters of a String by rearranging the characters
Given a string str that consists of characters and spaces, the task is to find the minimum cost to reduce the number of spaces between characters of the string. Cost of moving a character for index i to index j is defined as: | i - j | Examples: Input: str = " @ $" Output: 4 Explanation: As the characters are at indices [2, 7] (only two), either mo
7 min read
Modify string by inserting characters such that every K-length substring consists of unique characters only
Given string S of size N consisting of K distinct characters and (N - K) '?'s, the task is to replace all '?' with existing characters from the string such that every substring of size K has consisted of unique characters only. If it is not possible to do so, then print "-1". Examples: Input: S = "????abcd", K = 4Output: abcdabcdExplanation:Replaci
6 min read
Modify string by replacing all occurrences of given characters by specified replacing characters
Given a string S consisting of N lowercase alphabets and an array of pairs of characters P[][2], the task is to modify the given string S by replacing all occurrences of character P[i][0] with character P[i][1]. Examples: Input: S = "aabbgg", P[][2] = {{a, b}, {b, g}, {g, a}}Output: bbggaaExplanation:Replace 'a' by 'b' in the original string. Now t
12 min read
Article Tags :
Practice Tags :