字符串编码 -- 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

 

你可能感兴趣的:(字符串,面试)