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?

More than 5 years have passed since last update.

C++でのsubstrのサンプル

Posted at

C++でsubstrのサンプルを見るとマジックナンバー使うのが当たり前みたいに感じてしまうけど、現場でそれやられると辛いです。書いてて辛くないのでしょうか。

私は間違えそうなので、文字数なんて数えたくないです。
ということで、下記のような数えないサンプルを考えて見ました。

main.cpp
// #include <string.h>
#include <iostream>

using namespace std;

int main(int argc, char* argv[]) {
  const string sample = "20180707_000001_param0_param12345";

  // よくあるサンプル
  string sub = sample.substr(16, 6);
  cout << sub << endl;

  // 位置、サイズを人間が数えないサンプル
  const string date_part = "YYYYMMDD";
  const string id_part = "IDXXXX";
  const string param0_part = "PARAM0";
  const string param1_part = "PARAM1XXXX";

  string pre_str = "";

  string date = sample.substr(pre_str.size(), date_part.size());
  // 下記のようにsubstrの中で埋め込んだほうが読みやすいかも。
  // string date = sample.substr(pre_str.size(), string("YYYYMMDD").size());
  // string date = sample.substr(pre_str.size(), strlen("YYYYMMDD"));
  pre_str += (date + "_");

  string id = sample.substr(pre_str.size(), id_part.size());
  pre_str += (id + "_");

  string param0 = sample.substr(pre_str.size(), param0_part.size());
  pre_str += (param0 + "_");

  string param1 = sample.substr(pre_str.size(), param1_part.size());

  cout << date << ", " << id << ", " << param0 << ", " << param1 << endl;

  return 0;
}

マジックナンバーのサンプルの量が多すぎて焼け石に水ですが、
少しでもそんなコードを減らせればと思います。

0
0
7

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?