0
1

More than 5 years have passed since last update.

部分文字列を取得する

Posted at

始めに

Haskellで高階関数を組み合わせて部分文字列を作る例が全然わからなかったから考えたをみて、部分文字列の切り出しを命令型言語で行ったらどうなるのか興味が湧いたので、Javaで実装してみました

実装したソース

まずは2重ループでべたに実装してみました

MyFunctionTest2.java
package test;

import java.util.ArrayList;
import java.util.List;

public class MyFuncTest2 {
    public static void main(String args[])throws Exception{
        String sample = "ABCDE";
        System.out.println(execute(sample));
    }

    public static List<String> execute(String str)throws Exception{
        List<String>stringList = new ArrayList<String>(); 
        int size = str.length();
        //外側のループは切り出し位置の開始を決定しています
        for(int KIRIDASHI_START =0; KIRIDASHI_START<size;KIRIDASHI_START++){
            //内側のループは切り出し位置の終了を決定しています
            for(int KIRIDASHI_END =1; KIRIDASHI_END < (size -KIRIDASHI_START+1); KIRIDASHI_END++){
                stringList.add(str.substring(KIRIDASHI_START, KIRIDASHI_START + KIRIDASHI_END,str));
            }
        }
        return stringList;
    }
    public static String parseString(int start,int end,String str){
        System.out.println("開始:"+start + " 終了:"+end);
        return str.substring(start,end) + " ";
    }

}

後で自分の書いたソースを見直すと切り出し位置の取得と文字列の切り出しのロジックは別の関数に定義したほうが、プログラムの抽象度が上がる、と感じたので、ソースを書き直しました

MyFunctionTest2.java
package test;

import java.util.ArrayList;
import java.util.List;

public class MyFuncTest2 {
    public static void main(String args[])throws Exception{
        String sample = "ABCDE";
        System.out.println(execute(sample));
    }

    public static List<List<Integer>> makeList(String str)throws Exception{
        List<List<Integer>> kridashi = new ArrayList<List<Integer>> (); 
        int size = str.length();
        //外側のループは切り出し位置の開始を決定しています
        for(int KIRIDASHI_START =0; KIRIDASHI_START<size;KIRIDASHI_START++){
            //内側のループは切り出し位置の終了を決定しています
            for(int KIRIDASHI_END =1; KIRIDASHI_END < (size -KIRIDASHI_START+1); KIRIDASHI_END++){
                List<Integer>list = new ArrayList<Integer>();
                //切り出し位置の先頭をリストに格納する
                list.add(KIRIDASHI_START);
                //切り出し位置の終端をリストに格納する
                list.add(KIRIDASHI_START + KIRIDASHI_END);
                kridashi.add(list);
            }
        }
        return kridashi;
    }

    public static List<String> execute(String str) throws Exception{
        List<String>list = new ArrayList<String>();
        for(List<Integer>ichilist :makeList(str)){
            list.add(str.substring(ichilist.get(0),ichilist.get(1)));
        }
        return list;
    }
}

終わりに

実際に、Javaで実装してみてHaskellの実装と比較してみると言語の思想の違いがわかって面白いです。
命令型言語の場合、データ構造においてデータの位置を意識して実装する場面が多いようです

0
1
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
1