gpt4 book ai didi

c - 寻找一种更好的方法来移动 C 中的字符数组

转载 作者:行者123 更新时间:2023-11-30 14:54:25 25 4
gpt4 key购买 nike

为即将到来的 C 语言测试进行练习。编写一个程序来移动字符串中的每个字母(c 中的字符数组)。

例如,如果我想将“a”移动 3,那么它将是“d”。该程序运行良好,但在我看来,它有点“残酷”的解决方案。知道如何以更好/更优雅的方式完成这项任务吗?我想到了使用指针/字符串库函数/getchar,但我仍然是新手,所以不确定如何实现它们。

有更好的解决方案吗?寻找指南/想法,您不需要为我编写任何代码。提前致谢。

#define N 3

int shifter(char a[],int n,int shift,char b[]);

int main(){

char a[N] = {'h','e','y'};
char b[N];
int shift = 3;
shifter(a,N,shift,b);
int i;
for(i=0;i<N;i++){
printf("%c",b[i]);
}

return 0;
}

int shifter(char a[],int n,int shift,char b[]){

int i;

for(i=0;i<N;i++){
if(a[i]>= 65 && a[i]<=90){
if (a[i]+shift > 90)
b[i] = (a[i]+shift)-26;
}
else b[i] = a[i]+shift;
if (a[i]>=97 && a[i]<= 122){
if(a[i]+shift > 122)
b[i] = (a[i]+shift)-26;
}
else b[i] = a[i]+shift;
}
return b;

}

最佳答案

更喜欢使用字母而不是数字:

if (a[i] >= 'a' and a[i] <= 'z')

注意你的流程。目前您有

if (is lower) ...
else b[i] = something;

if (is upper) ...
else b[i] = something;

您可以将其组合成一个 if 并避免重复内容:

if      (is lower) b[i] = ...
else if (is upper) b[i] = ...
else b[i] = ...

如果允许,您还可以通过 #include 并使用 isupper()islower() 来确定角色的类别。

最后,您可以使用一些模运算来简化表达式。

b[i] = ((a[i] - 'a') + shift) % 26 + 'a';

就我个人而言,我会编写一个函数来执行此操作:

char shift( char c, int shift )

使用上述函数,您可以拥有一个非常漂亮的 if 语句...

:哦)

关于c - 寻找一种更好的方法来移动 C 中的字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46751447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com