Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

java - how to convert from str.substring(0, i) into str.charAt()? (to make equal)

I tried in many times but don't know how to change str.substring(0,i) into str.charAt(i) Please help I tried to make a result as below but I struggle from str.substinrg(0,i) to str.charAt(i) If i would like to make a result as below, at this point, how should i have to change it?

repeatFront("Chocolate", 4) → "ChocChoChC"
repeatFront("Chocolate", 3) → "ChoChC"
repeatFront("Ice Cream", 2) → "IcI"

below code is not successfully correct

public String repeatFront(String str, int n) {

    int i;
    String newStr;

    for(i = 0; i < str.length(); i++)
    {
        newStr = Character.toString(str.charAt(n));
    }
    return str;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have no clue if thats what you wanted, but the outputs are correct:

public static String repeatFront(String str, int n) {
    String newStr = "";

    for(int i = n; i > 0; i--) {
        for(int i2 = 0; i2 < i; i2++) {
            newStr = newStr + str.charAt(i2);
        } 
    } 

    return newStr;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...