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!

6
  • 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. Commented Mar 24, 2022 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. Commented Mar 24, 2022 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 is an example for removing all space characters. Commented Mar 24, 2022 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! Commented Mar 24, 2022 at 19:23
  • Does this answer your question? Delete whitespace from string Commented Apr 1, 2022 at 5:31

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.