问题描述:
输入字符串例如:there is a pig,,,.,pig is good.
输出:there is a pig good
去掉字符串中所有非字母的字符,并删去重复单词
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *change(char *str)
{
if (str == NULL)
{
return NULL;
}
int len = strlen(str);
char *p[1024] = { 0 };
int count = 0;
for (int i = 0; i < len; i++)
{
if (!((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')))//不是字母的变为空格
{
str[i] = ' ';
}
}
char *temp = str;
while (*temp == ' ')
{
temp++;
}
p[count++] = temp;//查找并指向第一个不位空格的字符
while (*temp != '\0')
{
if (*temp != ' ')
{
temp++;
}
else
{
*temp++ = '\0';//将字符后的空格置为\0
while (*temp == ' ')//过滤掉多余的空格
{
temp++;
}
if (*temp == '\0')//如果末尾有很多,遇到/0退出
{
break;
}
p[count++] = temp;//指向空格后的第一个字符
}
}
for (int i = 0; i < count - 1; i++)
{
for (int j = i + 1; j < count; j++)
{
if (p[i] != NULL && p[j] != NULL)
{
if (strcmp(p[i], p[j]) == 0)//重复字符置空
{
memset(&p[j], 0, 4);
}
}
}
}
char *return_str = (char *)malloc(sizeof(char) * 1024);
if (return_str == NULL)
{
return NULL;
}
memset(return_str, 0, 1024);
for (int i = 0; i < count; i++)
{
if (p[i] != NULL)
{
strcat(return_str, p[i]);
strcat(return_str, " ");
}
}
int last_len = strlen(return_str);
return_str[last_len - 1] = '\0';
return return_str;
}
void test()
{
char str[1024] = { " there is is" };
char *p = change(str);
if (p == NULL)
{
return;
}
printf("%s", p);
if (p != NULL)
{
free(p);
p = NULL;
}
}
void main()
{
test();
system("pause");
}