Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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));
    }
    
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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,%20int)

Thus, the length of the substring is endIndex-beginIndex

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading