简体   繁体   中英

Index of substring start point?

I am completely new to Java, had never seen computer code till one week ago, I managed to put together this code, but cannot quite get my head round the following concept:

When representing my first substring to start at int F , it would make more sense to me for the code to execute correctly at F = s.length(); , not +1 , because s is 11 characters. The index that starts one after the d and print nothing is s.length()+1; , but it seems as though that would start at two indexes after the word has finished. Like my second substring, when it executes, G will be at 3, meaning it will start at the second l and fill the gap as required. Can anyone clear this up for me?

Thank you.

public class Main {
    public static void main(String[] args) {
        String s = "hello world";
        String rep = s.replaceAll("[a-z]", " ");
        int F = s.length()+1;
        int G = 2;

        for(int i = 0; i<s.length(); i++, F--, G++)
            if (i == 0 || i >= s.length()-1){
                System.out.println(s);
            } else {
                System.out.println(s.charAt(0) + rep.substring(F) + s.charAt(i) + 
                    rep.substring(G) + s.charAt(s.length()-1));
            }
    }
}

You're thinking is correct; for doing your substrings, F should start at s.length() . The reason you need to add a + 1 is because you go through the loop once before you get to your substring code.

The first time you go through your loop, you print out s and continue. Now on your second iteration, i = 1 , G = 3 , and F = s.length() , because the for loop has added 1 to i and G and subtracted 1 from F .

So, in reality, the substring part you are concerned with does start with F = s.length() , it just is hard to see in your code.

Here is a modified version of your code, which does the same thing, but starts with F = s.length() .

public class Main {
    public static void main(String[] args) {
        String s = "hello world";
        String rep = s.replaceAll("[a-z]", " ");
        int F = s.length();
        int G = 3;

        System.out.println(s);
        for(int i = 1; i<s.length()-1; i++, F--, G++)
            System.out.println(s.charAt(0) + rep.substring(F) + s.charAt(i) +
                rep.substring(G) + s.charAt(s.length()-1));
        System.out.println(s);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM