题解 | #字符串变形#
字符串变形
https://www.nowcoder.com/practice/c3120c1c1bc44ad986259c0cf0f0b80e
C语言
//大小写转换
#define UPPER_LOWER(c) ((c >= 'a' && c <= 'z') ? (c-'a'+'A') : (c-'A'+'a'))
/**
*
* @param s string字符串
* @param n int整型
* @return string字符串
*/
char* trans(char* s, int n ) {
// char res[17]={0};
// printf("n = %d, input : %s", n, s);
// write code here
char *res = (char*)malloc(sizeof(char)*(n+2));
int wordLen = 0; //单词长度
char tmpc;
char *pCur;
//先整个字符串反转
for(int i=0; i<n; i++){
if(s[i] != ' ' && s[i] != '\0')
res[n-1-i] = UPPER_LOWER(s[i]);
else
res[n-1-i] = s[i];
}
res[n] = '\0'; //设置结束符
res[n+1] = '\0'; //设置结束符
pCur = res; //用pCur表示当前位置
while(*pCur != '\0')
{
wordLen = 0; //重置单词长度
while(*pCur != ' ' && *pCur != '\0'){ //获得单词长度
wordLen++;
pCur++;
}
for(int j=0; j<wordLen/2; j++){ //单词倒序
tmpc = pCur[-j-1];
pCur[-j-1] = pCur[-wordLen+j-1+1];
pCur[-wordLen+j-1+1] = tmpc;
}
pCur++; //跳过空格
}
return res;
}