[英]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.