1.描述
输入一串字符串, 用下面的方法进行重新编码:
1.仅对字符串中处于 'A' - 'Z'以及'a'-'z'范围内的字符进行编码,其他字符直接过滤掉
2. 若子串包含连续k个相同的字符X,则改为Xk; 其中X为这个子串中唯一的字符.
3. 如果子串中字符仅为1个时, 则后面的'1'则省去.
*输入格式*
直接输入1行字符串并且长度都小于 1000.
*输出格式*
对于输入字符串, 输出编码后的字符串.
*样例输入*
1;4AB3C
A`12BB[][CCC
*样例输出*
ABC
AB2C3
2.代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#define MAXSIZE 1000
/*
* 字符统计
*
* 参数说明:
* inputString -- 待编码的字符串
* outputString -- 编码后的字符串
*/
void string_encode(char* inputString, char* outputString)
{
/* TODO: write code as below */
/* TODO: 字符统计 */
char ch = 0;
int count = 1;
int len = strlen(inputString);
int i = 0;
int j = 0;
char buf[8] = { 0 };
for (;i < len;i++) {
ch = inputString[i];
if (!isupper(ch) && !islower(ch)) {
continue;
}
if ((i + 1 < len) && (ch == inputString[i + 1])) {
++count;
}
else {
outputString[j++] = ch;
if (count > 1) {
snprintf(buf, sizeof(buf), "%d", count);
strcpy(outputString + j, buf);
j += strlen(buf);
}
count = 1;
}
}
}
int main()
{
char* sInput = NULL;
char* sOutput = NULL;
printf("Please input string:\n");
//TODO:write your code here
int size = sizeof(char) * MAXSIZE;
sInput = (char *)malloc(size);
if (NULL == sInput) {
return -1;
}
sOutput = (char *)malloc(size);
if (NULL == sOutput) {
return -1;
}
memset(sInput, 0, size);
memset(sOutput, 0, size);
fgets(sInput, size, stdin);
printf("original string is:%s", sInput);
printf("\n");
string_encode(sInput, sOutput);
printf("after count:%s", sOutput);
printf("\n");
free(sInput);
free(sOutput);
}
3.编译
Makefile:
DBG = #-ggdb3
OPTFLAGS = -Wall -Wextra -Wstrict-prototypes -Wmissing-prototypes $(DBG) -pedantic
SRC = stringencode.c
TARGET = stringencode
OBJ = $(SRC:.c=.o)
default: $(TARGET)
%.o: %.c
$(CC) $(CFLAGS) -c -o $@ $<
$(TARGET): $(OBJ)
$(CC) -o $@ $(OBJ) $(LDFLAGS)
clean:
rm $(OBJ) $(TA
4.运行测试