user14285182
user14285182

Reputation: 25

How to delete specific character from c string without converting to string?

I am trying to delete a specific character (:), which occurs twice in my c string, from a c string without converting it to a string.

So far I tried to do the following but it's deleting every character after (:), which is not what I am trying to do. I'm just trying to take out that specific character.

// cString = 09:24:46

for (int i = 0; i < strlen(cString); i++){
        cString[2] = '\0';
        cString[5] = '\0';
    }
//current output: 09
//desired output: 092446

What should I make cString[2] and cString[5] equal to? I tried putting them equal to NULL but I get the same output and I also tried spaces but I want the output to have no spaces

Upvotes: 0

Views: 758

Answers (3)

PaulMcKenzie
PaulMcKenzie

Reputation: 35454

You don't need to convert the C-style string to std::string to "remove" characters.

You could use the std::remove algorithm function:

#include <algorithm>
#include <iostream>
#include <cstring>

int main()
{
  char cString[] = "09:24:46";
  std::cout << cString << "\n";

  // "Remove" the ':' from the C-style string.  
  // pos will point to the beginning of the "removed" elements 
  auto pos = std::remove(cString, cString + strlen(cString), ':');
  
  // overwrite the removed elements with 0 
  while (*pos)
     *pos = '\0';

  std::cout << cString;
} 

Output:

09:24:46
092446

Upvotes: 2

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38834

const size_t n = strlen(cString);
for (size_t i = 0, j = 0; j <= n; j++) {
  if (cString[j] != ':')
    cString[i++] = cString[j];
}

Upvotes: 0

Staz
Staz

Reputation: 358

'\0' in a character array indicates it's ending. It won't print any further characters.

You can shift all the remaining characters one index back and mark the last character as '\0' (null).

Like so:

for(int i = 0;i < n;i++){
     if(cString[i] == ':'){
         for(int j = i;j < n-1;j++){
               cString[j] = cString[j+1];
         }
         cString[n-1] = '\0';
         break;
     }
}

Upvotes: 1

Related Questions