Modifying character in String
Last Updated :
07 Oct, 2023
Given a string str, an integer index, and a character ch, the task is to modify the character at index in a given string and replace it with character ch.
Examples:
Input: str = “geeksforgeeks”, index = 0, ch = ‘G’
Output: Geeksforgeeks
Input: str = “spacing”, index = 2, ch = ‘*’
Output: sp*cing
Approach: To solve the problem follow the below idea:
Assign the character ‘ch’ at index given in the problem.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void modifyString(string& s, char ch, int index)
{
if (index < s.length())
s[index] = ch;
}
int main()
{
string s = "geeksforgeeks";
int index = 0;
char ch = 'G' ;
modifyString(s, ch, index);
cout << s << endl;
}
|
Java
import java.io.*;
public class Main {
public static void modifyString(StringBuilder s,
char ch, int index)
{
if (index < s.length())
s.setCharAt(index, ch);
}
public static void main(String[] args)
{
StringBuilder s
= new StringBuilder("geeksforgeeks");
int index = 0 ;
char ch = 'G' ;
modifyString(s, ch, index);
System.out.println(s);
}
}
|
Python3
def modify_string(s, ch, index):
if index < len (s):
s[index] = ch
if __name__ = = "__main__":
s = list ("geeksforgeeks")
index = 0
ch = 'G'
modify_string(s, ch, index)
print (''.join(s))
|
C#
using System;
class Program
{
static void ModifyString( ref string s, char ch, int index)
{
if (index < s.Length)
s = s.Substring(0, index) + ch + s.Substring(index + 1);
}
static void Main( string [] args)
{
string s = "geeksforgeeks" ;
int index = 0;
char ch = 'G' ;
ModifyString( ref s, ch, index);
Console.WriteLine(s);
}
}
|
Javascript
function GFG(s, ch, index) {
if (index < s.length) {
const stringArray = s.split(' ');
// Modify the character at the specified index
stringArray[index] = ch;
// Join the array back into a string
s = stringArray.join(' ');
}
return s;
}
// Driver code
function main() {
let s = "geeksforgeeks";
let index = 0;
let ch = ' G';
s = GFG(s, ch, index);
console.log(s);
}
main();
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...