C语言实现 字符编码

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.运行测试

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值