Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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

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

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));
    }
}
hina0118
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away