我不知道我怎么会开始解决这个问题,
例如,
字符串"Hello Worlld"
应该是
"Helo World"
假设您可以重复一次单词,
hhhhiiii frieend - 允许每个单词每个字母重复两次 将会 hhii frieend
我甚至不确定从哪里开始我必须在c
中对此进行编码编辑: 功能标题
void ReduceString(char *word, int Maximum)
EDIT2: 不区分大小写, 仅限于stdio.h和string.h 最大连续字符数有限制,所有连续字符超过此最大数字 应该被淘汰。
答案 0 :(得分:1)
简单的解决方案:
void x(char *s, int n)
{
char *cp= s;
int i, j;
while (*cp) {
i= 1;
while (*(cp+i) && ((*(cp+i))&~32)==((*cp)&~32)) i++; // count character repeat
for (j=0; j<n && j<i; j++) // repeat at most max repeat (n)
*s++ = *(cp+j);
cp += i;
}
*s= '\0';
}
编辑:添加了最大重复次数(n)
编辑:不区分大小写:&~32
删除ASCII中的小写位(这将使我得到混淆的C价格)。
答案 1 :(得分:0)
计算连续字符,如果重复次数不超过限制则输出字符。
#include <stdio.h>
#include <string.h>
/* this function make alphabet lower and make it not case sensitive */
/* note that tolower, which is in ctype.h, is not available here */
char normalizeAlphabet(char in)
{
static const char* upperAlphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const char* lowerAlphabets = "abcdefghijklmnopqrstuvwxyz";
int index = -1;
int i;
for (i = 0; upperAlphabets[i] != '\0'; i++)
{
if (in == upperAlphabets[i])
{
index = i;
break;
}
}
if (index >= 0)
{
return lowerAlphabets[index];
}
else
{
return in;
}
}
void ReduceString(char *word, int Maximum)
{
char *out = word;
int currentRepetition = 0;
int doNotOutput = 0;
char currentChar = '\0';
char normalizedChar;
while (*word != '\0')
{
normalizedChar = normalizeAlphabet(*word);
if (normalizedChar == currentChar)
{
/* continuous same characters */
if (currentRepetition < Maximum)
{
currentRepetition++;
}
else
{
doNotOutput = 1;
}
}
else
{
/* hit to another character */
currentChar = normalizedChar;
currentRepetition = 1;
doNotOutput = 0;
if (Maximum < currentRepetition) doNotOutput = 1;
}
if (!doNotOutput)
{
/* if repetition is not touching the limit, output the character */
*out = *word;
out++;
}
word++;
}
*out = '\0';
}
int main(void)
{
char input[1024];
char buf[1024];
while (fgets(input, sizeof(input), stdin))
{
int i;
printf("input : %s", input);
for (i = 1; i < 5; i++)
{
strcpy(buf, input);
ReduceString(buf, i);
printf("reduced Maximum = %d : %s", i, buf);
}
}
return 0;
}