简体   繁体   中英

I have a string and I want to remove any - ,( ,) ,& ,$ ,# ,! ,[ ,] ,{ ,} ," ,' from the beginning or end of the word

Each word is a string, there is no white space between them since each word is read using scanf.

If it is between the words just ignore those.

For example:

"..!Hello!!!."

would produce

Hello

and

"??Str'ing!!"

would produce

   Str'ing

Since I'm a beginner, I'm only allowed to use loops and the standard <string.h> header in C.

I already made a helper function that keeps reading each index and returns true if the character matches any of the ones listed above so far.

I have this so far but it removes punctuation from the entire code and not just the beginning and end of words:

void punc(char *str) {
    char *pr = str;
    char *pw = str;
    while (*pr) {
        *pw = *pr++;
         pw += (is_punc(*pw) == false);
    }
    *pw = '\0';
}

A good way to do it is to shave off all punctuation characters from the front and the back of the char array, for this sample I'm using your pointers, moving them along the char array till the first non-punctuation character is found, null terminate it and return the pointer to the 1st non-punctuation character:

Live sample

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

char *punc(char *str)
{
    int iterations = 0;
    char *pr = str;                   
    char *pw = &str[strlen(str) - 1]; //pointer to str end
    while (ispunct(*pr))  // I'm using ctype.h ispunct() standard function here 
    {                     // You can repalce it by your helper function    
        pr++;
        printf("it%d ", iterations++); //count and print iterations
    }
    while (ispunct(*pw))
    {      
        if(pw <= pr){  //using pointer comparison to avoid unnecessary iterations
           break;
        }
        pw--;
        printf("it%d ", iterations++);  //count and print iterations
    }   
    *(pw + 1) = '\0';
    return pr;
}

int main()
{
    char str1[] = ".[],!hello-.,?!-worl.d.?(!.";  //test1
    char str2[] = "!.';?";                        //test2   
    char *result1, *result2; 

    result1 = punc(str1);
    printf("  %s\n", result1);    
    result2 = punc(str2);
    printf("  %s\n", result2);    
    strcpy(str1, result1);  //if you want to really replace str with new string   
    return 0;
}

Output:

it0 it1 it2 it3 it4 it5 it6 it7 it8 it9   hello-.,?!-worl.d
it0 it1 it2 it3 it4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM