How to remove the character at a given index from a string in C?
memmove
can handle overlapping areas, I would try something like that (not tested, maybe +-1 issue)
char word[] = "abcdef";
int idxToDel = 2;
memmove(&word[idxToDel], &word[idxToDel + 1], strlen(word) - idxToDel);
Before: "abcdef"
After: "abdef"
How can I remove certain characters from a string in C?
You are thinking in the right direction, you have just confused the logic for deleting. In your case where you consider the tags to be is_deleting
you only want to copy characters when not deleting.
Rather than considering if your condition is_deleting
why not consider whether you are intag
. At least when iterating over characters, being either in at tag ignoring characters or not in a tag copying characters seems a bit more descriptive.
Regardless you have 3 conditions for the current character. It is either (1) a '<'
indicating a tag-opening where you set your intag
flag true, or (2) the intag
flag is true and the current character is '>'
marking the close of the tag, or (3) intag
is false and you are copying characters. You can implement that logic as follows:
When looping over the characters in any string, there is no need to take the strlen()
. The nul-terminating character marks the end of the string for you.
If you put that together, you could do:
#include <stdio.h>
char *rmtags (char *s)
{
int intag = 0, /* flag in-tag 0/1 (false/true) */
write = 0; /* write index */
for (int i = 0; s[i]; i++) { /* loop over each char in s */
if (s[i] == '<') /* tag opening? */
intag = 1; /* set intag flag true */
else if (intag) { /* if inside a tag */
if (s[i] == '>') /* tag close */
intag = 0; /* set intag false */
}
else /* not opening & not in tag */
s[write++] = s[i]; /* copy to write index, increment */
}
s[write] = 0; /* nul-terminate s */
return s; /* convenience return of s */
}
int main (void) {
char s[] = "<p>sample_text</p>";
printf ("text: '%s'\n", rmtags (s));
}
(note: You don't want to reinvent the wheel to parse html. See Parse html using C and particularly gumbo-parser. In this limited simple example -- it is trivial, but nested tags spanning multiple lines wildly complicate this endeavor quickly. Use a library that validates html)
Example Use/Output
$ ./bin/html_rmtags
text: 'sample_text'
How to remove all occurrences of a given character from string in C?
You can do it like this:
void remove_all_chars(char* str, char c) {
char *pr = str, *pw = str;
while (*pr) {
*pw = *pr++;
pw += (*pw != c);
}
*pw = '\0';
}
int main() {
char str[] = "llHello, world!ll";
remove_all_chars(str, 'l');
printf("'%s'\n", str);
return 0;
}
The idea is to keep a separate read and write pointers (pr
for reading and pw
for writing), always advance the reading pointer, and advance the writing pointer only when it's not pointing to a given character.
Searching for and removing certain characters from strings in C++
Problem with current code:
str.erase(str[i], 0);
This is incorrect. Let's look at string::erase
function's signature in this case:
basic_string& erase( size_type index = 0, size_type count = npos );
First argument is size_type
, which is basically an unsigned long integer. It is the index of the char you want to remove. Second one is also of the same type and it is the number of chars you want to remove from the index
position, which is 1. What you are passing to the function is str[i]
which is of char
type which is incorrect.
Fixed version:
str.erase(i, 1);
Additionally:
finder = find(vowels, vowels + 10, active);
std::find
returns an iterator, don't assign it char*
even if it compiles. Fixed:
auto finder = find(vowels, vowels + 10, active);
You can also use the ready made algorithms from the standard template library(STL) to solve this problem in one line:
Just use remove_if
along with string::erase
:
std::string str = "hello, world";
str.erase (std::remove_if (str.begin (), str.end (), [](char c)
{
return c == 'a' || c == 'e' || c == 'i'
|| c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I'
|| c == 'O' || c == 'U';
}),
str.end ());
std::cout << str;
As mentioned by @PaulMckenzie, using the erase-remove
idiom here is faster(twice as fast) than the loop variant + erase
. Benchmark on quick-bench So, why is it faster?
Suppose we have the string: "Hello cpp"
Using erase()
, every time we 'erase' a character, all the characters after it need to be moved back one position. In this case, we need to remove 'e' and 'o', position 1 and position 4.
- Remove char from position 1 and move char 2 to char 8, one position back. That means we moved 7 chars.
- Remove char from position 4 and move chars 5 to char 8 one position back. That means we moved 4 chars.
- Total: 11 chars moved
remove
works differently. It simply just moves back the elements that are not to be removed in the beginning, possibly overwriting the ones that are going to be removed. This results in much less moving around of elements making it faster.
See this SO Post for a more detailed and better explanation.
Note: You need #include <algorithm>
for this.
Remove specified char from strings in C
This code works on my compiler :
#include<stdio.h>
#include<conio.h>
#define MAX_LINE_LENGTH 1024
#define MAX_STR_LENGTH 4
void removeChar(char *str, char c) {
int i = 0;
int j = 0;
while (str[i]) {
if (str[i] != c) {
str[j++] = str[i];
}
i++;
}
str[j]=0;
}
void convertStrings(char line[][MAX_STR_LENGTH]) { //change 1
for (int str = 0; str < MAX_LINE_LENGTH; ++str) {
for (int ch = 0; ch < MAX_STR_LENGTH; ++ch) {
if (line[str][ch] == 'r') {
removeChar(line[str], 'r');
}
}
}
}
int main() {
char line[3][MAX_STR_LENGTH] = {"pep", "rol", "rak"}; //change 2
printf("%s\n", line[1]);
convertStrings(line);
printf("%s\n", line[1]);
getch();
return 0;
}
How to remove certain characters from a string in C++?
string str("(555) 555-5555");
char chars[] = "()-";
for (unsigned int i = 0; i < strlen(chars); ++i)
{
// you need include <algorithm> to use general algorithms like std::remove()
str.erase (std::remove(str.begin(), str.end(), chars[i]), str.end());
}
// output: 555 5555555
cout << str << endl;
To use as function:
void removeCharsFromString( string &str, char* charsToRemove ) {
for ( unsigned int i = 0; i < strlen(charsToRemove); ++i ) {
str.erase( remove(str.begin(), str.end(), charsToRemove[i]), str.end() );
}
}
//example of usage:
removeCharsFromString( str, "()-" );
Related Topics
Determine the Size of a C++ Array Programmatically
Heterogeneous Containers in C++
Const& , & and && Specifiers For Member Functions in C++
C++ Template Partial Specialization Member Function
Convert an Int to Ascii Character
What Belongs in an Educational Tool to Demonstrate the Unwarranted Assumptions People Make in C/C++
How to Compile C Code With Anonymous Structs/Unions
When to Pass by Reference and When to Pass by Pointer in C++
Static Constructors in C++? I Need to Initialize Private Static Objects
How to Print Utf-8 from C++ Console Application on Windows
How to Find Memory Leak in a C++ Code/Project
How to Check If a C++ String Is an Int
Difference Between Undefined Behavior and Ill-Formed, No Diagnostic Message Required