우선 다음 소스는 Java용 소스를 //// 표시가 붙은 줄 한 줄만 수정하여 Groovy영 소스로 고친 것이다.

[파일명:  testStringFindApp.groovy]------------------------------------------------
import java.util.*;

public class TestStringFindApp {

    public static void main(String[] args) {
        String[] words = [ "하나", "둘", "셋", "넷", "다섯", "여섯" ] as String[];   ////
        int where;

        System.out.print("array: ");
        printArray(words);
        where = find(words, "셋");
        if (where > 0) {
            System.out.print("발견!  ");
            System.out.println("Next word of 셋 in array: " + words[where+1]);
        }

        System.out.println("Sorting...");
        Arrays.sort(words);

        System.out.print("array: ");
        printArray(words);
        where = find(words, "셋");
        if (where > 0) {
            System.out.print("발견!  ");
            System.out.println("Next word of 셋 in array: " + words[where+1]);
        }
    }

    static int find(String[] arr, String s) {
     for (int i = 0; i < arr.length; i++) {
      if (arr[i].indexOf(s) >= 0)
       return i;
     }
     return -1;
    }

    static void printArray(String[] arr) {
        System.out.print("[");
        for (int i = 0; i < arr.length - 1; i++) {
            System.out.print(arr[i] + ", ");
        }
        if ( arr.length > 0)
            System.out.print(arr[arr.length - 1]);
        System.out.println("]");
    }
}
------------------------------------------------


실행> groovy testStringFindApp.groovy
array: [하나, 둘, 셋, 넷, 다섯, 여섯]
발견!  Next word of 셋 in array: 넷
Sorting...
array: [넷, 다섯, 둘, 셋, 여섯, 하나]
발견!  Next word of 셋 in array: 여섯



그리고 다음 소스는 위의 Groovy용 소스를 더 Grovy 소스 코드답게 짧게 만든 것이다.

[파일명:  testStringFindApp.groovy]------------------------------------------------
def find(String[] arr, String s) {
   for (int i = 0; i < arr.length; i++) {
     if (arr[i].indexOf(s) >= 0)
      return i;
    }
    return -1;
}

def printArray(String[] arr) {
    print("[");
    for (int i = 0; i < arr.length - 1; i++) {
        print(arr[i] + ", ");
    }
    if (arr.length > 0)
        print(arr[arr.length - 1]);
    println("]");
}

String[] words = [ "하나", "둘", "셋", "넷", "다섯", "여섯" ] as String[]
int where

print("array: ")
printArray(words)
where = find(words, "셋")
if (where > 0) {
    print("발견!  ")
    println("Next word of 셋 in array: " + words[where+1])
}

println("Sorting...")
Arrays.sort(words)

print("array: ")
printArray(words)
where = find(words, "셋")
if (where > 0) {
    print("발견!  ")
    println("Next word of 셋 in array: " + words[where+1])
}
------------------------------------------------


실행> groovy testStringFind.groovy
array: [하나, 둘, 셋, 넷, 다섯, 여섯]
발견!  Next word of 셋 in array: 넷
Sorting...
array: [넷, 다섯, 둘, 셋, 여섯, 하나]
발견!  Next word of 셋 in array: 여섯


크리에이티브 커먼즈 라이선스
Creative Commons License

 


Posted by Scripter
,