Home > database >  range of substring method in java [duplicate]
range of substring method in java [duplicate]

Time:09-27

I wrote a program that outputs substrings for school and got the same output for both substrings, which I thought wasn't supposed to be the case.

public class Substrings {
   public static void main(String[] args) {
      String str = "CSE 110 Principles of Programming";
      String courseTitle1;
      String courseTitle2;

      courseTitle1 = courseInfo.substring(8);
      courseTitle2 = courseInfo.substring(8, str.length());
      
      System.out.printf("Course Title 1 : %d\n", courseTitle1);
      System.out.printf("Course Title 2 : %d\n", courseTitle2);

I know the first index is inclusive, but isn't the index of the last character (given by str.length() supposed to be exlusive? So shouldn't the output be "Principles of Programmin" instead of "Principles of Programming"??

CodePudding user response:

The characters in a string are numbered 0 to length-1. For example, "cat" has length=3, and the characters are numbered 0, 1, 2.

So, in a call to substring(8, length), because the end index is 'exclusive', you'll get characters 8, 9, ... to length-1, which is the characters up to and including the last one in the string.

CodePudding user response:

Java string indexes are zero-based, therefore str.length() is actually one past the last character, therefore courseInfo.substring(8, str.length()) gives from the 9th character to the end of the string.

CodePudding user response:

The substring method's second parameter is the first index you do not want to be included in the substring. Since Java is zero-indexed, excluding the lengthth character still keeps the last character, which is character length-1.

When you exclude the second parameter of substring, it's implying that its value is string.length(). That's why courseTitle1 keeps everything till the end of the string.

CodePudding user response:

Arrays are zero-based indexes, so you have to minus one to get that effect.

public class StackOverflow {
    public static void main(String[] args) {
        String courseInfo = "CSE 110 Principles of Programming";
        String str = "CSE 110 Principles of Programming";
        String courseTitle1;
        String courseTitle2;

        courseTitle1 = courseInfo.substring(8);
        courseTitle2 = courseInfo.substring(8, str.length()-1);

        System.out.println("Course Title 1 : %d\n"  courseTitle1);
        System.out.println("Course Title 2 : %d\n"  courseTitle2);
    }
} 
  • Related