LoginSignup
0
0

More than 5 years have passed since last update.

C言語で小文字を大文字にして出力する

Last updated at Posted at 2017-05-18

はじめに

C言語でswitch文を使って大文字小文字変換をするエンジニアがいたみたいな記事が上がってたので試しにswitch文を使わない方法を書いてみた

コード

main.c
#include <stdio.h>
 
int main(void) {
  const char DIFF = 'a' - 'A'; /* 32 */
  const char ch = 't';
  printf("%c", ch - DIFF);
  return 0;
}

DIFF を定義したのは 32 が何を意味しているのかを明示するためなのでぶっちゃけ

main.c
#include <stdio.h>
 
int main(void) {
  printf("%c", 't' - 32);
  return 0;
}

でいい

見つけ方

test.c
#include <stdio.h>

int main(void) {
  printf("%d\n", 'a' - 'A'); /* 32 */
  printf("%d\n", 't' - 'T'); /* 32 */
  return 0;
}

なんでもいいので大文字と小文字の引き算をすると32という数字が出てくる
これをヒントにすれば解けるはず
ASCIIコードを知らなくても物は試しで
四則演算や剰余演算、シフト演算、ビット演算をやってみることが 手抜き 効率的な問題解決 への近道になる

おわりに

C言語で const って使えたっけ? ってくらい久しぶりにC言語書いた

0
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0