Deletion of character in String using Loop
Traverse the string and push all the characters to another string or character array except the character which needs to be deleted. We will shift the characters to the left starting from the specified position to delete the character.
Step-by-step algorithm:
- Initialize a character array to store the modified string.
- Traverse the original string character by character.
- If the current index matches the specified position, skip the character.
- Otherwise, copy the current character from the original string to the modified string.
- Null-terminate the modified string.
Below is the implementation of the algorithm:
#include <iostream>
#include <cstring>
using namespace std;
string delete_char_cpp(string s, char ch) {
string new_str = "";
for (char c : s) {
if (c != ch) {
new_str += c;
}
}
return new_str;
}
int main() {
string s = "hello";
char ch = 'l';
cout << delete_char_cpp(s, ch) << endl; // Output: "heo"
return 0;
}
#include <stdio.h>
#include <string.h>
char* deleteCharC(char* s, char ch) {
int i, j;
int len = strlen(s);
for (i = j = 0; i < len; i++) {
if (s[i] != ch) {
s[j++] = s[i];
}
}
s[j] = '\0';
return s;
}
int main() {
char s[] = "hello";
char ch = 'l';
printf("%s\n", deleteCharC(s, ch)); // Output: "heo"
return 0;
}
class DeleteCharJava {
public static String deleteCharJava(String s, char ch) {
StringBuilder newStr = new StringBuilder();
for (char c : s.toCharArray()) {
if (c != ch) {
newStr.append(c);
}
}
return newStr.toString();
}
public static void main(String[] args) {
String s = "hello";
char ch = 'l';
System.out.println(deleteCharJava(s, ch)); // Output: "heo"
}
}
def delete_char_python(s, char):
new_str = ""
for c in s:
if c != char:
new_str += c
return new_str
# Example Usage
s = "hello"
char = "l"
print(delete_char_python(s, char)) # Output: "heo"
function deleteCharJS(s, char) {
let newStr = "";
for (let c of s) {
if (c !== char) {
newStr += c;
}
}
return newStr;
}
// Example Usage
let s = "hello";
let char = "l";
console.log(deleteCharJS(s, char)); // Output: "heo"
Output
Modified string: GeeksorGeeks
Time Complexity: O(n) where n is the length of the string.
Auxiliary Space: O(n) where n is the length of the string.
Deletion of character in String
Given a string str
and an integer position pos
, the task is to delete the character at the specified position pos
from the string str
.
Examples:
Input: str = “w3wiki”, pos = 5
Output: GeeksorGeeksInput: str = “HelloWorld”, pos = 0
Output: elloWorld
Contact Us