![]() The extracted portion starts with the character at the index beginIndex till the end of the string. Otherwise the substring() method will simply throws IndexOutOfBoundsException. The beginIndex should be greater than zero and less than the length of the string.Īlso, endIndex should be greater than or equal to beginIndex and less than the length of the given string. ![]() and lowers readability - for such a trivial shortcut of saving one single method parameter guido. When substring() Throws IndexOutOfBoundsException? You want to get the st1 string without last two characters, so when we use the substring() in Java we have to give the start point and end point of the sub-string. If we test the method in JUnit with concrete values looking at the C++ method, we expect: String testString 'testString' assertThat (testString. Please bear in mind that both methods are susceptible to throw IndexOutOfBoundsException. Specifying an endIndex of 10 should always throw the IndexOutOfBoundsException () because testString has no endIndex of 10. Public String substring(int startIndex, int endIndex): this variant accepts two parametersīeginIndex: describes the starting index, it’s inclusive for both variantsĮndIndex: denotes the last index and it’s exclusive The integer argument specifies the index of the first character. Public String substring(int startIndex): this version accepts only one parameter Returns a new string that is a substring of this string. String.substring() Syntax Variants in Javaīasically, there are two overloaded variants of the substring() method: So, let’s dig deep and take a close look at it. Now that we know what a substring is, let’s see how to create and manipulate it.įortunately, the String class provides a handy method called substring() especially to get a substring. In short, every subset or portion of an original string is called a substring.įor example, “devwithus” is composed of the following substrings: “dev”, “with”, “us”… What is a substring?Ī substring, as the name implies, is a contiguous sequence of characters within a particular string. So, this is where the substring() method comes to the rescue. We need just to manipulate some of them to solve one problem or another. However, sometimes we are not interested in all characters. But if the length of the string is higher than 6 than 6 will be returned. Math.min() gets the lowest value, this means that if the length of the string is lower than 6 that value is returned. ![]() String in Java is a class that represents a sequence of characters. secondName.lenght() gets the length of the String. In this article, we are going to shed light on Java String substring() method.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |