#include <stdio.h>
char s[] = "`1234567890-=QWERTYUIOP[]\\ASDFGHJKL;'ZXCVBNM,./";
int main ()
{
int i, c;
while ((c = getchar()) != EOF) {
for (i = 1; s[i] && s[i] != c; i++);
if (s[i]) putchar(s[i-1]);
else putchar(c);
/* code */
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
什么是s[i] && s[i] != c;
for循环内的条件是什么意思?
我以前没见过.谢谢!
首先,变量s
是一个空终止的C字符串,它是一个最后一个字符为chararcters的数组'\0'
.您可以使用i
代码中的索引访问该数组.
使用for循环,您循环遍历s
字符串,直到找到null终止符'\0'
或char c
.空终止符'\0'
为0十进制,这在布尔逻辑中表示为false,因为除了0之外的其他值为真.
如果你写的例如:
char a = 'A'; /* same as char a = 65; */
if (a) { ... }; /* same as if (a != 0) */
Run Code Online (Sandbox Code Playgroud)
这意味着:if a is true
哪个是:if a is not false
更好:if a is not equal to 0
.此语句将评估为true,因为它'A'
是65十进制(ASCII代码),不等于0.
您要求的for循环可以重写为:
for (i = 1; s[i] != '\0' && s[i] != c; i++);
Run Code Online (Sandbox Code Playgroud)
我建议使用显式语句,s[i] != '\0'
因为它更容易阅读.