Open In App

Remove a Character from a Given Position

Last Updated : 31 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given a string and and a position (0 based), remove the character at the given position.

Examples: 

Input : s = "abcde", pos = 1
Output : s = "acde"

Input : s = "a", pos = 0
Output : s = ""

Using Built-In Methods

We use erase in C++, string slicing in Python, StringBuilder Delete in Java, ubstring in Java and slice in JavaScript.

C++
#include <iostream>
using namespace std;

string removeCharAtPosition(string s, int pos) {
    if (pos < 0 || pos >= s.length()) {
        return s;
    }
    s.erase(pos, 1);
    return s;
}

int main() {
    string s = "abcde";
    int pos = 1;
    cout << "Output: " << removeCharAtPosition(s, pos) << endl; 
    return 0;
}
C
#include <stdio.h>
#include <string.h>

void removeCharAtPosition(char *s, int pos) {
    int len = strlen(s);
    if (pos < 0 || pos >= len) {
        return;
    }
    memmove(&s[pos], &s[pos + 1], len - pos);
}

int main() {
    char s[] = "abcde";
    int pos = 1;
    removeCharAtPosition(s, pos);
    printf("Output: %s\n", s);
    return 0;
}
Java
// Java program to demonstrate
// the deleteCharAt() Method.

class GFG {
	public static void main(String[] args)
	{

		// create a StringBuilder object
		// with a String pass as parameter
		StringBuilder s
			= new StringBuilder("abcde");


		// print string after removal of Character
        // at index 1 
		System.out.println(s.deleteCharAt(1));
	}
}
Python
def remove_char_at_position(s, pos):
    if pos < 0 or pos >= len(s):
        return s
    return s[:pos] + s[pos+1:]

s = "abcde"
pos = 1
print("Output:", remove_char_at_position(s, pos))
JavaScript
function removeCharAtPosition(s, pos) {
    if (pos < 0 || pos >= s.length) {
        return s;
    }
    return s.slice(0, pos) + s.slice(pos + 1);
}

let s = "abcde";
let pos = 1;
console.log("Output: " + removeCharAtPosition(s, pos));

Output
bbc

Writing Your Own Method

We move all characters after the given position, one index back. To do this we mainly do s]i] = s[i+1] for all indexes i after p.

C++
#include <iostream>
using namespace std;

void customRemoveCharAtPosition(string &s, int pos) {
  
    if (pos < 0 || pos >= s.length()) {
        return; 
    }

    // Shift characters to the left from the position
    for (int i = pos; i < s.length() - 1; i++) {
        s[i] = s[i + 1];
    }

    s.resize(s.length() - 1);
}

int main() {
    string s = "abcde";
    int pos = 1;
    customRemoveCharAtPosition(s, pos);
    cout << s << endl; 
    return 0;
}
Java
import java.util.*;
public class GFG {

    public static String removechar(String word, char ch)
    {
        StringBuilder s = new StringBuilder(word);
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ch) {
                s.deleteCharAt(i);
                i--;
            }
        }

        return s.toString();
    }

    // driver's code
    public static void main(String args[])
    {
        String word = "geeksforgeeks";
        char ch = 'e';
        System.out.println(removechar(word, ch));
    }
}
Python
# Remove character at specified position using a loop

def remove_char_at_position(s, p):
  
    # Check for valid position
    if p < 0 or p >= len(s): 
        return s

    # Convert string to list for mutable operations
    s_list = list(s)  
    
    # Shift characters to the left from the position
    for i in range(p, len(s) - 1):
        s_list[i] = s_list[i + 1]

    # Remove the last character
    s_list.pop()  
    
    return ''.join(s_list) 
  
s = "abcde" 
p = 1 
s = remove_char_at_position(s, p)  
print(s)  
JavaScript
// Remove character at specified position using a loop
function removeCharAtPosition(s, p) {

    // Check for valid position
    if (p < 0 || p >= s.length) 
        return s;

    // Convert string to array for mutable operations
    let sArr = s.split('');  
    
    // Shift characters to the left from the position
    for (let i = p; i < s.length - 1; i++) 
        sArr[i] = sArr[i + 1];

    // Remove the last character
    sArr.pop();  
    
    return sArr.join('');  // Convert array back to string
}

let s = "abcde"; 
let p = 1;  
s = removeCharAtPosition(s, p);  
console.log(s); 

Output
eeksforeeks

Time Complexity : O(n) where n is length of input string.
Auxiliary Space : O(1)


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg
  翻译: