2016-03-29 6 views
-3

Javaプログラムで4つのパラメータを使用するOracle INSTR fun?オラクルで

ケース1:

SELECT INSTR('Viveok Srinivoasamoorthy','o',15,1) FROM DUAL; 

出力:19

ケース2: SELECT INSTR( 'Viveok Srinivoasamoorthy'、 'O'、15,2)DUAL FROM。 出力:20

同じように、私は達成するために4つのパラメータ(文字列、部分文字列、start_positionとnthoccurrence)でjavaプログラムを開発する必要があります。

これは私が試したコードですが、私は、n番目のoccuranceを見つけることができないことができ、以下のコードで:

public static int nthoccur(String str1,String str2,int occurs) 
{ 
    int f_occurance=0; 
    f_occurance=str1.indexOf(str2, occurs-1)+1; 
    System.out.println("f_occurance Value------*** "+f_occurance); 
    return f_occurance;  
} 

public static void main(String args[]) 
{ 

int resultinst=nthoccur("Viveok Srinivoasamoorthy","o",15); 
System.out.println(resultinst); 
} 

出力:

f_occurance Value------*** 19 
19 

今、私は第二を見つけたいですJavaプログラムを使用して、文字列の15番目の位置から "o"を検出します。 Javaプログラムを使用してケース2を達成するにはどうすればよいですか?

+2

Stackoverflowは "あなたのための他の人が書くコード"サービスではありません。これまでに書いたコードを投稿してください。あなたがどこにいるのか教えてください。 「ステップ0で立ち往生して、始めるのを手伝ってください」はここでは受け入れられません。 – GhostCat

+0

コメントによって情報を追加しないでください。代わりに質問を編集してください。そして、まずはヘルプセンターに目を向けると、「良い質問」がどのように見えるかを理解するために時間を費やしてください。よい質問は良い答えを得る。悪い質問...そうではありません。 – GhostCat

答えて

1

INSTRのような方法があります。

コメントあなたはそれがどのように動作するかを理解するのに役立ちます、ステップバイステップ:

public static int instr(final String str, final String substring, int position, final int occurrence) { 

    // matches counter 
    int count = 0; 
    // index of last match 
    int indexFound = 0; 

    // while we haven't reached the desired match count, and we still find another match 
    while (count != occurrence && (indexFound = str.indexOf(substring, position)) != -1) 

    { 
     // increment match count 
     count++; 
     // position the next search index, to the end of the current match 
     position = indexFound + substring.length(); 

    } 

    if (count == occurrence) { 
     // the number of occurrences was matched, return the last match index 
     return indexFound + 1; // index in Java starts at 0 
    } else { 
     // the number of occurrences was not matched, return 0 
     return 0; 
    } 

} 
+0

@Bergerさん、どうもありがとうございました。 –

0

ここにはもう一つの方法です:-1には出現しないことを意味します。 getInstring(String input, String substr, int start, int occurence) { char[] tempstring = input.substring(start).replaceAll(substr, "-").toCharArray(); int occurindex = 0; int counter = 0; for (int i = 0; i < tempstring.length; i++) { if (":-".equals(":" + tempstring[i])) { occurindex++; counter = i; } if (occurindex == occurence) { break; } } return counter == 0 ? -1 : counter + start + 1; }

関連する問題