VOOZH about

URL: https://www.geeksforgeeks.org/dsa/how-to-insert-a-character-in-a-string/

⇱ Insert a character in String at a Given Position - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Insert a character in String at a Given Position

Last Updated : 6 Nov, 2024

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.


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.


Output
GeeAks

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

Comment
Article Tags:
Article Tags: