[英]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.每个单词都是一个字符串,它们之间没有空格,因为每个单词都是使用 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.由于我是初学者,我只允许在 C 中使用循环和标准的<string.h>
标头。
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.我已经创建了一个辅助函数,它会不断读取每个索引,如果该字符与上面列出的任何一个匹配,则返回 true。
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:一个很好的方法是从 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;
}
Output:输出:
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.