字符串编码 -- C语言

编码规则

Give an implementation of encoding a string which contains less than 20 chars. There three rules:

1. replace the alphabetical char in the string with the fourth char behind it, for example, a -> e ,A -> E, X -> B, y -> c, z -> d

2. if the char is not a alphabetical char, ignore it.

3. reverse the string updated

代码实现

static char lowerMap[26] = { \
	'a','b','c','d','e','f','g', \
	'h','i','j','k','l','m','n', \
	'o','p','q','r','s','t','u', \
	'v','w','x','y','z' \
};


static char upperMap[26] = { \
	'A','B','C','D','E','F','G', \
	'H','I','J','K','L','M','N', \
	'O','P','Q','R','S','T','U', \
	'V','W','X','Y','Z' \
};


int encodeStr(char * str){
	if(NULL == str){
		printf("encodeStr param error\n");
		return PARAM_ERR;
	}

	char * p = NULL;
	int dist = 0;

	p = str;
	while('\0' != *p){
		if(*p >= 'a' && *p <= 'z'){
			dist = *p - 'a';
			dist = dist + 4;
			dist = dist % 26;
			*p = lowerMap[dist];
		} else if (*p >= 'A' && *p <= 'Z'){
			dist = *p - 'A';
			dist = dist + 4;
			dist = dist % 26;
			*p = upperMap[dist];
			
		} else {
			
		}
		
		p++;
	}

	strReversWithWord(str);
	
	return SUCCESS;

}


void testencodeStr(void){
	char str[100] = "hasdxz11HYZ";

	printf("\n************  testencodeStr ************ \n");	

	encodeStr(str);

	printf("Encoded str is: %s\n", str);

	return;		
}

使用全局数组作为映射数组,同'a'或'A'的距离+4,作为数组下标;如果找过‘z’,通过取余的方式达到循环的目的

 

代码编译

gcc main.c str.c -g -o a.exe

调试输出


************  testencodeStr ************
Encoded str is: DCL11dbhwel

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值