我在for循环中大写了太多元素,但仅在特定索引上

问题描述 投票:0回答:1

我不知道为什么,但是在这种方法中,第5和第10个元素每次都被改写。我找不到原因。例如:传递“ ZpglnRxqenU”作为参数应返回:“ Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeeeee-Nnnnnnnnnnnn-Uuuuuuuuuuuu”,但返回:“ Z-Pp-Ggg-Lll -RRRRRR-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-UUUUUUUUUUUU“

请注意,R和U都大写,与其余字符不同。

/**
 * The purpose of this method is to receive a string, deconstruct it by characters
 * and save it in array, then iterate through this array creating a new string
 * where each character will be represented the number of times equivalent to its
 * position in the array + 1 while upperCasing every 1st occurrence of the character
 * and separating every set of character repetitions with "-".
 * @param string
 * @return String
 */
public String builder (String string){

    /*
    Here we split the string we receive by characters and save these characters in
    a new array called strArr.
     */
    String[] strArr = string.split("");
    String finalString = "";

    /*
    We iterate through the array of characters adding "-" each time we start to
    represent a new character.
    We add the characters N times where N is the order of appearance in the string
    we receive as param.
     */
    for (int i = 0; i < strArr.length; i++) {
        if(i > 0){
            finalString += "-";
        }
        for (int j = 0; j < i + 1; j++) {
            if(j == 0){
                /*
                this is upperCasing every 5th and 10th character for some reason
                 */
                // TODO: 26/12/2019 stop upperCasing 5th and 10th element. 
                finalString += strArr[i].toUpperCase();
                continue;
            }
            finalString += strArr[i];
        }
    }
    return finalString;
java arrays string for-loop uppercase
1个回答
0
投票

您必须首先添加以下行:string = string.toLowerCase();

公共字符串生成器(字符串字符串){

 string = string.toLowerCase();
/*
Here we split the string we receive by characters and save these characters in
a new array called strArr.
 */
String[] strArr = string.split("");
String finalString = "";

/*
We iterate through the array of characters adding "-" each time we start to
represent a new character.
We add the characters N times where N is the order of appearance in the string
we receive as param.
 */
for (int i = 0; i < strArr.length; i++) {
    if(i > 0){
        finalString += "-";
    }
    for (int j = 0; j < i + 1; j++) {
        if(j == 0){
            /*
            this is upperCasing every 5th and 10th character for some reason
             */
            // TODO: 26/12/2019 stop upperCasing 5th and 10th element. 
            finalString += strArr[i].toUpperCase();
            continue;
        }
        finalString += strArr[i];
    }
}
return finalString;

}

© www.soinside.com 2019 - 2024. All rights reserved.