Home > Net >  How to replace special character in an array with the next non-special character?
How to replace special character in an array with the next non-special character?

Time:11-20

I'm trying to concatenate an inputted char array to another in order to reverse my string and check if it's a palindrome, but I want to skip over special characters. When my for loop hits a special character, it stops reading the rest of the string.

Output example 1

Output example 2

This is what my for loop looks like

    for(i=0; i < strlen(original); i  )
    {
        if((original[i] >= 49 && original[i] <= 57) || (original[i] >= 97 && original[i] <= 122))
        {
            cleaned[i] = original[i];
        }
        
        else if(original[i] >= 65 && original[i] <= 90)
        {
            cleaned[i] = original[i]   32;
        }
        
        else if((original[i] >= 33 && original[i] <= 47) || (original[i] >= 58 && original[i] <= 64) || (original[i] >= 91 && original[i] <= 96) || (original[i] >= 123 && original[i] <= 126))
        {
            continue;
        }
    }

"Cleaned" is meant to hold the original string characters with lowercased letters and ignored special characters.

Is there some way I can move to the next non-special character and replace the space of the first special character?

CodePudding user response:

You need two indices: one for the array you're reading from and the other for the array you're writing to. If you use the same index for both, you'll end up with unset slots in your output array. Presumably these happen to be 0 in this case, prematurely terminating the output string.

CodePudding user response:

Let's look at

          012345
original: a!bb!a
cleaned:  abba
          0123

You want the program to have the same effect as the following:

cleaned[0] = original[0];
// Skip      original[1];
cleaned[1] = original[2];
cleaned[2] = original[3];
// Skip      original[4];
cleaned[3] = original[5];
cleaned[4] = 0;

As you can see, cleaned[i] = original[i]; can't possibly be right. The offset in the original string is going to be different from the offset in the cleaned string, so you need to have two indexes or pointers.

  • Related