Faced the following misunderstanding, when porting code to c # under java. It is necessary to extract a substring from a string of characters, take, starting from a certain k-th position of n-characters. Actually, the code:

str = "((15+3)+14/2+(7*2)+3^2+(12+(7*2)))"; System.out.println(str.substring(27, 5)); 

For me, as a person who is somewhat familiar with Sharp, the code is quite understandable and logical. In line 33 characters, in fact, I need to get a substring with 27 - a character (32 characters each). But as a result, I get an OutOfBoundException error. And even if I want to take 3 characters from 10 position. What could be the problem?

    4 answers 4

    According to the java documentation , the substring method takes 2 parameters: the starting index — where to start cutting from, and the ending index — to where to cut.

     substring(int beginIndex, int endIndex) 
        public String substring(int beginIndex, int endIndex) 

      The substring method takes the beginning and the end, not the beginning and the number of characters.

        Understood, I just very badly know java. It is necessary to specify the position of characters in the array explicitly, and not the number of elements that I would like to take as in c #.

          To display the last 5 characters will help the code:

           System.out.println(str.substring(str.length()-5, str.length())); 
          • one
            "from the 27th position 5 characters" ≠ "last 5 characters". - Nick Volynkin ♦
          • Yes. I was inattentive. - LS