An implementation of the C language string alternative usage
- 2020-06-12 10:07:59
- OfStack
To start with this example, let's look at a simple program:
String array to realize number to letter:
#include <stdio.h>
#include <string.h>
int main(void)
{
int num = 15 ;
//26 A letter
const char str[] = "abcdefghijklmnopqlstuvwxyz" ;
// The way to do this is to num this 10 The base number is converted to letters by taking the mode and output, from the program, you can know is the output p
char a = str[num%26] ;
printf("a=%c\n",a);
return 0 ;
}
And of course we could write it this way, in terms of Pointers:
#include <stdio.h>
#include <string.h>
int main(void)
{
int num = 15 ;
char *str = "abcdefghijklmnopqlstuvwxyz" ;
char a = str[num%26] ;
printf("a=%c\n",a);
return 0 ;
}
Again, the result is the same as above, let's simplify this method, if the beginner's foundation is not solid, perhaps 1 confused.
#include <stdio.h>
#include <string.h>
int main(void)
{
int num = 15 ;
//char *str = "abcdefghijklmnopqlstuvwxyz" ;
char a = "abcdefghijklmnopqlstuvwxyz"[num%26] ;
printf("a=%c\n",a);
return 0 ;
}
Not surprisingly, this means exactly the same as the previous two, but replaces str with a string. Because of this, you can use this technique when you write a hexadecimal transformation, but as a developer, I'm not a big fan of writing readable code.
If you could write it this way up here, you could write it this way down here, and the output would be four threes.
#include <stdio.h>
int main(void)
{
char *p = "0123456789abcdef" ;
putchar(p[3]);
// A newline
putchar('\n');
putchar(*(p + 3));
putchar('\n');
putchar("0123456789abcdef"[3]);
putchar('\n');
putchar(*("0123456780abcdef"+3));
putchar('\n');
return 0 ;
}
conclusion