Sure! Below are the implementations of the provided C++ code in Python, Java, C#, JavaScript, and C, adhering to your specified constraints.
Python
def insertChar(s, c, pos):
ans = ""
for i in range(len(s)):
# Insert the character at the given position
if i == pos:
ans += c
# Insert the original characters
ans += s[i]
# If the given pos is beyond the length,
# append the character at the end
if pos >= len(s):
ans += c
return ans
def main():
s = "abc"
c = 'G'
pos = 3
result = insertChar(s, c, pos)
print("Modified string:", result)
if __name__ == "__main__":
main()
Java
class GfG {
static String insertChar(String s, char c, int pos) {
String ans = "";
for (int i = 0; i < s.length(); i++) {
// Insert the character at the given position
if (i == pos) {
ans += c;
}
// Insert the original characters
ans += s.charAt(i);
}
// If the given pos is beyond the length,
// append the character at the end
if (pos >= s.length()) {
ans += c;
}
return ans;
}
public static void main(String[] args) {
String s = "abc";
char c = 'G';
int pos = 3;
String result = insertChar(s, c, pos);
System.out.println("Modified string: " + result);
}
}
C#
using System;
class GfG
{
static string insertChar(string s, char c, int pos)
{
string ans = "";
for (int i = 0; i < s.Length; i++)
{
// Insert the character at the given position
if (i == pos)
{
ans += c;
}
// Insert the original characters
ans += s[i];
}
// If the given pos is beyond the length,
// append the character at the end
if (pos >= s.Length)
{
ans += c;
}
return ans;
}
static void Main(string[] args)
{
string s = "abc";
char c = 'G';
int pos = 3;
string result = insertChar(s, c, pos);
Console.WriteLine("Modified string: " + result);
}
}
JavaScript
function insertChar(s, c, pos) {
let ans = "";
for (let i = 0; i < s.length; i++) {
// Insert the character at the given position
if (i == pos) {
ans += c;
}
// Insert the original characters
ans += s[i];
}
// If the given pos is beyond the length,
// append the character at the end
if (pos >= s.length) {
ans += c;
}
return ans;
}
function main() {
let s = "abc";
let c = 'G';
let pos = 3;
let result = insertChar(s, c, pos);
console.log("Modified string:", result);
}
main();
C
#include <stdio.h>
#include <string.h>
void insertChar(char s[], char c, int pos, char ans[]) {
int len = strlen(s);
int j = 0;
for (int i = 0; i < len; i++) {
// Insert the character at the given position
if (i == pos) {
ans[j++] = c;
}
// Insert the original characters
ans[j++] = s[i];
}
// If the given pos is beyond the length,
// append the character at the end
if (pos >= len) {
ans[j++] = c;
}
ans[j] = '\0';
}
int main() {
char s[] = "abc";
char c = 'G';
int pos = 3;
char result[100];
insertChar(s, c, pos, result);
printf("Modified string: %s\n", result);
return 0;
}
Each implementation maintains the original variable names and comments, with a single line space before each comment as requested. Let me know if you need any further assistance!