0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C++で使う文字列⇄数値変換まとめ(AtCoder用)

Posted at

C++で使う文字列⇄数値変換まとめ(AtCoder用)

基本方針

  • 桁数が大きい / 先頭0がある / 部分一致を見るstringで持つ
  • 1文字=1桁'0' を引く
  • 数値にする必要がないならしない

char → int(1桁の数字)

使用用途

  • 数字列の各桁を扱う
  • 各桁の差・和・回転数を計算

使い方

int x = S[i] - '0';

何をしている?

  • '0''9' は連続した文字コード
  • '7' - '0' = 7

使うポイント

  • S[i]必ず数字文字のときだけ使う
  • 速い・安全・例外なし

ダメな例

stoi(string(1, S[i]))  // 遅い・冗長

int → char(数字を1文字に)

使用用途

  • 数字を文字として出力
  • 文字列を組み立てる

使い方

char c = '0' + x;  // xは0〜9

ポイント

  • x が 0〜9 であることを保証する

string → int / long long(全体を数値化)

使用用途

  • 桁数が小さいと保証されている
  • 数値として計算したい

使い方

int x = stoi(s);
long long y = stoll(s);

ポイント(重要)

  • 例外を投げる
  • 範囲オーバーでRE
  • 先頭0はOK("0012" → 12

AtCoderでの判断基準

状況 使う?
桁数 ≤ 18 が保証
制約に保証なし
文字列として処理可能

4. string → 数値 (自前パース)

使用用途

  • 例外を絶対に避けたい
  • 制約が不安
  • 負号なしと保証されている

使い方

long long x = 0;
for(char c : s) {
    x = x * 10 + (c - '0');
}

ポイント

  • 競プロでは stoiより安全
  • 先頭0もOK

5. int / long long → string

使用用途

  • 出力用
  • 文字列処理と混ぜる

使い方

string s = to_string(x);

ポイント

  • 迷ったらこれ
  • AtCoderで困ることはほぼない

6. char ↔ string (1文字)

使用用途

  • charstring として扱いたい
  • substrstoi に渡す

使い方

char c = '7';
string s(1, c);  // "7"
char c = s[0];   // s.size() >= 1 が前提

部分文字列 → 数値

使用用途

  • 連続した数値部分を取り出す

使い方

int x = stoi(S.substr(l, len));

ポイント

  • lenが大きいと危険
  • 本当に数値にする必要があるか考える

チェックリスト

競プロ用テンプレ

int digit(char c) {
    return c - '0'; // '0'..'9' 前提
}

char digit_char(int d) {
    return char('0' + d); // 0..9 前提
}
0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?