0

Im having problems with this piece of code

string_array[1001] = "Hello Everyone6415!"; 
      for (i = 0; i < 1000; i++) {
        if (isdigit(string_array[counter])) {
          string_array[counter] = ' ';
          counter++;
        } else {
          string_array[counter] = string_array[counter];
          counter++;

Output:Hello Everyone    !

Is there a way to replace the numbers with nothing at all?

Tried to use another counter, new array, NULL. What am I expecting the code to do is to print Hello Everyone!

Nimantha
  • 6,405
  • 6
  • 28
  • 69
  • You simply have to copy the later characters, together with a null terminator, over the ones that are to be deleted. `memmove()` can help if you know what the length is. There's no O(1) solution unless you switch from ordinary C strings to some more elaborate data structure. – Nate Eldredge Mar 24 '22 at 18:45
  • Well, that's the problem. I posted a very heavily edited small piece of my code so it would be easier to read. In my original code, the array_string is user input using fgets. – Adam Jakubík Mar 24 '22 at 18:47
  • 1
    You iterate through the string, keeping two counters. You read from one and write to the other. If the character is one you want to remove, you increment the read counter only; otherwise you copy the character and increment both. [Here](https://stackoverflow.com/a/5501698/634919) is an example for removing all space characters. – Nate Eldredge Mar 24 '22 at 19:02
  • Thanks a lot! My problem is solved. I knew it would be something simple but as I was coding for almost half a day, I stopped seeing the most simple solutions. Have a great day/night/evening! – Adam Jakubík Mar 24 '22 at 19:23
  • Does this answer your question? [Delete whitespace from string](https://stackoverflow.com/questions/5501501/delete-whitespace-from-string) – Nimantha Apr 01 '22 at 05:31
  • Hi @AdamJakubík if you found a solution to your problem, you can help the community by [answering your own question](https://stackoverflow.com/help/self-answer). – Andy J Apr 01 '22 at 05:35

1 Answers1

0

Fixing your code:

#include <stdio.h>
#include <ctype.h>

int main() {
   char string_array[1001] = "Hello Everyone6415!"; 
      for (int i = 0; i < 1000; i++) {
        if (isdigit(string_array[i])) {
          string_array[i] = ' ';
        }
      }
   printf("Output: %s",string_array);
}
ingdc
  • 760
  • 10
  • 16