简体   繁体   中英

question about the length of strings in java

I got a question about the Strings in Java:

new String(array, 0, end)

here, I don't know why we use 'end' instead of end-1? I mean, the array I want to store(0, end - 1).

If you look inside String.java , you could see that the third parameter is count

public String(char value[], int offset, int count)

value[] - input char array
offset - from which position you want the chars to be copied
count - number of chars to copy

So if you have a char[] of size 10, you could create a string as follows

new String(input, 0, 10); // NOT new String(input, 0, 9);

Although you misunderstood the use of the count feature, your question does raise a feature that is common throughout Java and other languages as well. Most ranges go from a to b where a is inclusive and b is exclusive.

The following example, albeit contrived, shows how this can help.

String.substring() is one such example:

Notice subsequent calls of substring use the previous ending index as the start of the next. This makes it easy to think about concatentating strings.

      String str = "encyclopedia";
      String newstr1 =
            str.substring(0, 3) + str.substring(3, 6) + str.substring(6);
      String newstr2 =
            str.substring(0, 2) + str.substring(2, 4) + str.substring(4);

      System.out.println(str);
      System.out.println(newstr1);
      System.out.println(newstr2);

All three print statement print encyclopedia

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