Home > Blockchain >  while using substring to print a character pattern why has i been initialized to 1 instead of 0?
while using substring to print a character pattern why has i been initialized to 1 instead of 0?

Time:04-21

I understand this program the only doubt is in the part where i has been initialized to 1. As strings are stored like arrays the place at 0 should have the first character of the string right ? then why is it one. i would appreciate if you could also help me with understanding how substring method works :)).

sample input: SCHOOL sample output: S SC SCH SCHO SCHOO SCHOOL

 /*taking SCHOOL as example and print S SC SCH ...*/
import java.util.*;
public class substring
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("enter a string");
        String word = sc.next();
        
        int x= word.length();
        
        for( int i = 1; i<=x; i  )
        System.out.println(word.substring(0,i));
    }
    
}

CodePudding user response:

In the String.substring (int begIndex, int endIndex) method, endIndex doesn't index the last character of the substring. It indexes the character after the last character of the substring.

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int, int)

Thus, the length of the substring is endIndex-beginIndex

  • Related