算法入门经典例题3-2,例题3-3知识点

3-2打印出输入字母在键盘上的左侧字母值

#include<stdio.h>
#include<string.h>


int main()
{
    char a[] = "`1234567890-=QWERTYUIOP[]\\ASDFGHJKL;'ZXCVBNM,./\0";
    char c ;
    while((c = getchar()) != EOF)
    {
          if(c == ' ')
          {
              printf(" ");
              continue;
          }
          for(int i = 0 ; i<strlen(a);i++)
          {
                if(c == a[i])
                {
                    //putchar(a[i-1]);
                    printf("%c",a[i-1]);
                }
          }
    }
     return 0;
}
/*
 #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);
     }
     return 0;
}

*/

1.新思想:可以定义一个变量,利用for循环不满足条件终止的特点,找到不满足的值

2.putchar() 输出字符(只能是一个字符量)


3-3(回文词)

#include<stdio.h>
#include<string.h>
#include<ctype.h>
const char* rev = "A   3  HIL JM O   2TUVWXY51SE Z  8 ";
const char* msg[] = {"not a palindrome", "a regular palindrome", "a mirrored string", "a mirrored palindrome"};


char change(char ch){
    if(isalpha(ch))  return rev[ch - 'A'];
    return rev[ch - '0' + 25];
}




int main()
{
      int stop,length;


      char str[30];
      while(scanf("%s",str)!=EOF)                          //注意字符串数组不需要加&符号
      {
           int x = 1;                                                   //注意每次均需初始化
           int y = 1;
           length = strlen(str);
           stop = (length+1)/2;

           for(int i = 0; i < stop ;i++)                    // 注意字符下标从0开始,所以下

                                                                         //标要往前移动一格

           {
                  if(str[i]!=str[length-1-i])  x = 0;
                  if(change(str[i]) != str[length-1-i])   y = 0;
           }
           printf("%s -- is %s.\n\n",str, msg[y*2+x]);
      }
      return 0;
}

1.新知识点:头文件ctype.h中定义的isalpha、isdigit、isprint等工具可以用来判断字符属性,而toupper、tolower等工具可以用来转换大小写。

https://blog.csdn.net/lgl125/article/details/6780098    (有关ctype.h的相关函数)

2.新想法:如果ch是大写字母,则ch-'A'就是它在字母表中的序号(A的序号是0,B的序号是1,依次类推);类似的,如果ch是数字,则ch-‘0’就是这个数字的本身。

注意:此题中的指针问题还未弄懂

#include<stdio.h>
int main()
{
     char a = 'a';
     char c = 'b';


     char x[] = "12345678";
     printf("%d",'d' - 'a');


}


// 当需要返回值为字符ACSII的编码值时,可以直接使用字符-字符的方式
// 例如:'c' - 'a' == 2;


猜你喜欢

转载自blog.csdn.net/m0_37632283/article/details/80025188