正如标题所说,%s工作不正常。这是一场代码战,因此%s需要能够使用数组来通过示例测试用例;无法更改playPass的函数声明。使用Ascii表。此外,在main((中打印的for循环也能工作,并为我提供正确的输出。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// takes a string and shifts letter n value;
// lower cases every other element if it contains a letter
// replaces number with a 9 complement
// returns array with values reversed.
char* playPass(char* s, int n)
{
int length = strlen(s);
char *pass= (char *)malloc(length*sizeof(char)+1);
char a;
int letter, i;
for(i=0; i< length; i++)
{
a = s[i];
letter = a;
if( letter >= 65 && letter <=90 )
{
letter +=n;
if(letter >90)
{
letter -=90;
letter +=64;
}
if((i+1) % 2 == 0 )
{
letter += 32;
}
a = letter;
}
else if(letter >= 48 && letter <= 57)
{
letter -= 48;
letter = 9 - letter;
a = letter + '0';
}
pass[length - i] = a;
}
return pass;
}
// answer should be
int main (){
char* s ={"I LOVE YOU!!!"};
int length = strlen(s);
int k = 1;
s =playPass( s,k );
int i;
printf(" %s", s);
for(i = 0; i <= length; i++)
{
printf(" %c", s[i]);
}
}
%s
仅适用于空终止的char *
char* playPass(char* s, int n) {
…
for() {
…
}
pass[i] = ' '; //Null terminate here.
return pass;
}
所以想明白了。
将新值分类到新阵列的末尾
pass[length - i] = a;
使得它从未向第一个元素写入值,因此
pass[0]= NULL;
不得不将其更改为
pass[length - (i-1)] = a;
感谢大家的帮助,我还清理了神奇数字中的代码。很棒的提示@phuclv!