LoginSignup
7
8

More than 5 years have passed since last update.

[車輪の再発明]固定長文字列の解析

Last updated at Posted at 2014-06-09

お仕事ではまだまだ固定長文字列でやりとりすることが多いので
固定長文字列からデータを切り出すクラスを作成。

どのプロジェクトでも一生懸命ロジッククラスで文字列を切り出してるけどめんどくさいないんだろうか。。。

FixedLengthStringParser.java
package tool;

/**
 * 固定長文字列パーサ
 */
public class FixedLengthStringParser {

    /** 固定長文字列 */
    private final String source;
    /** 現在位置 */
    private int position = 0;

    /**
     * コンストラクタ
     * @param source 固定長文字列
     */
    public FixedLengthStringParser(String source) {
        this.source = source;
    }

    /**
     * 次の文字列を切り出す
     * @param length 長さ
     * @return 切り出した文字列
     */
    public String next(int length) {
        if (source == null) {
            return null;
        }
        if (length < 1) {
            return null;
        }
        if (position >= source.length()) {
            return null;
        }
        String ret = null;
        if (position + length > source.length()) {
            ret = source.substring(position);
            position += length;
            return ret;
        }
        ret = source.substring(position, position + length);
        position += length;
        return ret;
    }

    /**
     * とりあえず動かす
     * @param args
     */
    public static void main(String[] args) {
        FixedLengthStringParser parser = new FixedLengthStringParser("abc123xyz");

        System.out.println(parser.next(3));
        System.out.println(parser.next(3));
        System.out.println(parser.next(0));
        System.out.println(parser.next(3));
        System.out.println(parser.next(5));
    }
}
7
8
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
7
8