使用Substring进行Java字符串分离

时间:2017-01-14 00:05:13

标签: java

这里我有这句话" THCUSATTYYE"并使用起始索引(美国)我想生成这样的字符串:

USATTYYE

SATTYYE

ATTYYE

到目前为止我有这个代码:

public class StringCheck {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        String phrase = "THCUSATTYYE";

        int useThisStart = phrase.indexOf("USA");
        String word =  new String ("");
        String word2 = new String ("");
        String word3 = new String ("");
        //First Loop
        for (int k = 3; k < phrase.length() - useThisStart-2; k += 3) {
            word =phrase.substring(useThisStart + k, useThisStart + k + 3);
        }
        //Secod Loop
        for (int k = 3; k < phrase.length() - useThisStart-2; k += 3) {
            word2 =phrase.substring(useThisStart + k + 1, useThisStart + k + 3 +1);
        }
        //Third Loop
        for (int k = 3; k < phrase.length() - useThisStart-2; k += 3) {
            word3 =phrase.substring(useThisStart + k + 2, useThisStart + k + 3+ 2);
        }
        System.out.println(word);
        System.out.println(word2);
        System.out.println(word3);
    }

}

但生成此输出: TTY

TYY

YYE

如何在我的代码示例中生成以下输出:

USATTYYE

SATTYYE

ATTYYE

4 个答案:

答案 0 :(得分:3)

你可以用一个变量和一个循环来做,例如:

public static void main(String[] args) throws Exception {
    String input = "THCUSATTYYE";
    String token = "USA";
    int index = input.indexOf(token);
    if(index != -1){
        String remainder = input.substring(index + token.length());
        for(int i=0 ; i<token.length() ; i++){
            System.out.println(token.substring(i) + remainder);
        }
    }
}

答案 1 :(得分:2)

你不需要使用for循环,你可以这样做:

word = phrase.substring(useThisStart, phrase.length())

然后分别:

word2 = phrase.substring(useThisStart+1, phrase.length())

word3 = phrase.substring(useThisStart+2, phrase.length())

你不需要给这个方法一个结束索引,在这种情况下你可以在没有它的情况下使用它。

答案 2 :(得分:2)

你可以这样吗

public static void main(String[] args) {
    String phrase = "THCUSATTYYE";
    String wordOfChoice = "USA";
    int wordOfChoiceCombos = wordOfChoice.length();
    int useThisStart = phrase.indexOf(wordOfChoice);

    while(wordOfChoiceCombos-- > 0 && useThisStart != -1)
         System.out.println(phrase.substring(useThisStart++));

}

输出

USATTYYE
SATTYYE
ATTYYE

答案 3 :(得分:2)

首先,测试是否找到了phrase。然后从初始位置开始使用一个循环,总共3次迭代。从开始索引打印substring。像,

String phrase = "THCUSATTYYE";
int useThisStart = phrase.indexOf("USA");
if (useThisStart > -1) {
    for (int i = useThisStart; i < useThisStart + 3; i++) {
        System.out.println(phrase.substring(i));
    }
}

输出(根据要求)

USATTYYE
SATTYYE
ATTYYE

,在Java 8+中,您可以使用IntStream.range之类的

if (useThisStart > -1) {
    IntStream.range(useThisStart, useThisStart + 3)
            .forEachOrdered(i -> System.out.println(phrase.substring(i)));
}