簡體   English   中英

我有一個字符串,我想刪除任何 - ,( ,) ,& ,$ ,# ,! ,[ ,] ,{ ,} ," ,' 從單詞的開頭或結尾

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

每個單詞都是一個字符串,它們之間沒有空格,因為每個單詞都是使用 scanf 讀取的。

如果是在單詞之間,請忽略那些。

例如:

"..!Hello!!!."

會產生

Hello

"??Str'ing!!"

會產生

   Str'ing

由於我是初學者,我只允許在 C 中使用循環和標准的<string.h>標頭。

我已經創建了一個輔助函數,它會不斷讀取每個索引,如果該字符與上面列出的任何一個匹配,則返回 true。

到目前為止,我已經有了這個,但它從整個代碼中刪除了標點符號,而不僅僅是單詞的開頭和結尾:

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

一個很好的方法是從 char 數組的前面和后面刮掉所有標點字符,對於這個示例,我使用你的指針,沿着 char 數組移動它們,直到找到第一個非標點字符, null 終止它並返回指向第一個非標點字符的指針:

現場樣品

#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;
}

輸出:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM