substring index range - java

Code:
public class Test {
public static void main(String[] args) {
String str = "University";
System.out.println(str.substring(4, 7));
}
}
Output: ers
I do not really understand how the substring method works. Does the index start at 0? If I start with 0, e is at index 4 but char i is at 7 so the output would be ersi.

0: U
1: n
2: i
3: v
4: e
5: r
6: s
7: i
8: t
9: y
Start index is inclusive
End index is exclusive
Javadoc link

Both are 0-based, but the start is inclusive and the end is exclusive. This ensures the resulting string is of length start - end.
To make life easier for substring operation, imagine that characters are between indexes.
0 1 2 3 4 5 6 7 8 9 10 <- available indexes for substring
u n i v E R S i t y
↑ ↑
start end --> range of "E R S"
Quoting the docs:
The substring begins at the specified
beginIndex and extends to the
character at index endIndex - 1. Thus
the length of the substring is
endIndex-beginIndex.

See the javadoc. It's an inclusive index for the first argument and exclusive for the second.

Like you I didn't find it came naturally. I normally still have to remind myself that
the length of the returned string is
lastIndex - firstIndex
that you can use the length of the string as the lastIndex even though there is no character there and trying to reference it would throw an Exception
so
"University".substring(6, 10)
returns the 4-character string "sity" even though there is no character at position 10.

public String substring(int beginIndex, int endIndex)
beginIndex—the begin index, inclusive.
endIndex—the end index, exclusive.
Example:
public class Test {
public static void main(String args[]) {
String Str = new String("Hello World");
System.out.println(Str.substring(3, 8));
}
}
Output: "lo Wo"
From 3 to 7 index.
Also there is another kind of substring() method:
public String substring(int beginIndex)
beginIndex—the begin index, inclusive.
Returns a sub string starting from beginIndex to the end of the main String.
Example:
public class Test {
public static void main(String args[]) {
String Str = new String("Hello World");
System.out.println(Str.substring(3));
}
}
Output: "lo World"
From 3 to the last index.

Yes, the index starts at zero (0). The two arguments are startIndex and endIndex, where per the documentation:
The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
See here for more information.

The substring starts at, and includes the character at the location of the first number given and goes to, but does not include the character at the last number given.

For substring(startIndex, endIndex), startIndex is inclusive and endIndex are exclusive. The startIndex and endIndex are very confusing.
I would understand substring(startIndex, length) to remember that.

public class SubstringExample
{
public static void main(String[] args)
{
String str="OOPs is a programming paradigm...";
System.out.println(" Length is: " + str.length());
System.out.println(" Substring is: " + str.substring(10, 30));
}
}
Output:
length is: 31
Substring is: programming paradigm

Related

What will be the output of String.substring(String.length)?

public class Str {
public static void main(String[] args) {
String str = "abcde";
String s = str.substring(str.length());
System.out.println(s);
}
}
The index of character 'e' is 4, but I am trying to get the whole string of length 5. If I execute the code above, why it is not throwing the IndexOutOfBoundsException?
The JavaDoc for String.substring() states:
[throws] IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
Since your beginIndex is equal to the length of the string it is a valid value and substring() returns an empty string.
The empty String ("" with length 0) is a valid String. So that is what is returned by your code.
In other words str.substring(str.length()-1); returns the string "e", and str.substring(str.length()); returns the empty string. Perfectly valid.
Assume you got a String:
Hello World
this is what the indicies look like:
H e l l o W o r l d
0 1 2 3 4 5 6 7 8 9 10
"Hello World" has length of 11 so str.length would be equal to 11 in this case
now there is no index 11 in there, in fact 11 is beyond the last index. thats why you receive a IndexOutOfBounds
Additionally str.substring(number) returns a substring STARTING from the specified number all the way to the end of the string.
so str.substring(4) in this case would return
o World
Just thought i should put that in here

java substring not working as expected

I'm trying to use substring function in java, but it keeps throwing an error, I want to know why ? the code seems to be good logically speaking but why it is throwing this error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
What I've read in the documentation substring takes 2 parameter
substring(whereIwantToStart,howManyCharactersToshow)
below is my code
String test = "160994";
System.out.println(test.substring(2,1)); //output should be 09 why error?
Can someone explain me what is wrong ? please I need explanation. Thanks :)
See the doc:
public String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and
extends to the character at index endIndex - 1. Thus the length of the
substring is endIndex-beginIndex.
You need "160994".substring(2, 4) to get 09.
End index should be greater than the Start Index. To get output as '09', you should provide the end index as 4 test.substring(2,4);
Returns a new string that is a substring of this string. The
substring begins at the specified beginIndex and extends
to the character at index endIndex - 1.
Thus the length of the substring is endIndex-beginIndex.
The StringIndexOutOfBoundsException will throw in below cases
beginIndex < 0
endIndex > value.length
endIndex - beginIndex < 0
For your required output use-
System.out.println(test.substring(2,4));
This is the format for the substring in java
public String substring(int beginIndex, int endIndex)
you are specifying start from index 2 and end at index 1 , that's why it's throwing an exception index out of range.
To get the output as 09 you need
System.out.println(test.substring(2,4));
Appendix - Java Docs https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)
public String substring(int startIndex, int endIndex): This method returns new String object containing the substring of the given string from specified startIndex to endIndex.
Let's understand the startIndex and endIndex by the code given below.
String s="hello";
System.out.println(s.substring(0,2));
Output : he
Notice :
endIndex > startIndex
in your case : change between 1 and 2 place to
String test = "160994";
System.out.println(test.substring(2, 4)); //output should be 09
Output : 09
String test = "160994";
System.out.println(test.substring(2,1));
Substring means (beginIndex, endIndex) and endIndex Should be larger than beginIndex.and your value(09) should be stay between beninIndex(which is starting index) and endIndex(Which is last index).
and you have taken endIndex 1 so you are geting the Error because your beginIndex is larger than endIndex.
if you want to get Ans. 09 then you should have to put endIndex 4.
Line will be:-System.out.println(test.substring(2,4));

StringIndexOutOfBoundsException when trying to get string from long string

I tried to get string from long string which is Firebase URL
"https://firebasestorage.googleapis.com/v0/b/No-manworld-3577.appspot.com/o/Contacts%2F1510361061636_Julien_Vcf?alt=media&token=c0bff20d-d115-4fef-b58c-4c7ffaef4296"
Now if you notice there is under score before and after name Julien in above string. I am trying to get that name but i am getting
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
Here is my piece of code
String s="https://firebasestorage.googleapis.com/v0/b/No-manworld-3577.appspot.com/o/Contacts%2F1510361061636_Julien_Vcf?alt=media&token=c0bff20d-d115-4fef-b58c-4c7ffaef4296";
String newName=s.substring(s.indexOf("_")+1, s.indexOf("_"));
System.out.println(newName);
As said in my comment, when using substring, the first number has to be smaller than the second one.
In your case, you are calling substring with x + 1 and x. x + 1 > x thus substring fails, with x being s.indexOf("_").
I understand that you are trying to get the second indexOf of _.
Here is code that would in your case yield Julien:
String s = "...";
int start = s.indexOf("_") + 1;
int end = s.indexOf("_", start);
// name will hold the content of s between the first two `_`s, assuming they exist.
String name = s.substring(start, end);
If requirements are not clear on which 2 _ to select then here is Java 8 Stream way of doing it ..
public class Check {
public static void main(String[] args) {
String s = "https://firebasestorage.googleapis.com/v0/b/No-manworld-3577.appspot.com/o/Contacts%2F1510361061636_Julien_Vcf?alt=media&token=c0bff20d-d115-4fef-b58c-4c7ffaef4296";
long count = s.chars().filter(ch -> ch == '_').count();
if (count == 2) {
System.out.println(s.substring(s.indexOf('_') + 1, s.lastIndexOf('_')));
} else {
System.out.println("More than 2 underscores");
}
}
}
Why your code didn't work?
Let assume s.indexOf("_") gets some positive number say 10 then below translates to ...
String newName=s.substring(s.indexOf("_")+1, s.indexOf("_"));
String newName=s.substring(11, 10);
This will give StringIndexOutOfBoundsException as endIndex < beginIndex for subString method.

String index out of range: -2

For the following program am getting exception:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -2
at java.lang.String.substring(String.java:1911)
at Names.main(Names.java:33)
for line
System.out.println("The character at index 3 in "+middle+" is "+middle.substring(3, 1));
Do you see any problem in this line?
/* Names.java */
import java.io.*;
public class Names {
/** Performs various string operations on the name John Fitzgerald kennedy.
*
* #param arg is not used
*/
public static void main(String[] args) {
String first = "john";
String middle = "Fitzgerald";
String last = "Kennedy";
String initials;
String firstInit, middleInit, lastInit;
firstInit = first.substring(0, 1);
middleInit = middle.substring(0,1);
lastInit = last.substring(0,1);
initials = firstInit.concat(middleInit);
initials = initials.concat(lastInit);
System.out.println();
System.out.println(first+" "+middle+" "+last+" ");
System.out.println(initials);
System.out.println(last+", "+first+" "+middle);
System.out.println(last+", "+first+" "+middleInit+".");
System.out.println(first.toUpperCase()+" "+last.toUpperCase());
System.out.println(first+" equals john is "+first.equals("john"));
System.out.println(first+" equals john (ignoring case is) "+first.equalsIgnoreCase("john"));
System.out.println("The character at index 3 in "+middle+" is "+middle.substring(3, 1));
System.out.println("The index of \"gerald\" within "+middle+" is "+middle.indexOf("gerald"));
System.out.println("The index of \"gerald\" within "+last+" is "+last.indexOf("gerald"));
System.out.println();
}
}
This isn't going to work:
middle.substring(3, 1)
You can't have an end value larger than your start value for String#substring():
Throws IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
Since you only want the character at index 3, use charAt() instead:
middle.charAt(3);
Or, using substring with a narrower range:
middle.substring(3, 4);
You have to pass (start, end) parameters to substring:
middle.substring(3, 4) // '4' since you just want one char
Remember that substring() won't return the char at index 4.
Note:
A simpler way to do this would be using charAt(index):
middle.charAt(3)
The method signature is
public String substring(int beginIndex, int endIndex)
So if you intend to take one character, you should use
middle.substring(3, 4);
From this documentation by oracle, it is clear that subString() method will throw IndexOutOfBoundsException if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
middle.substring(from index , to index) what your doing here middle.substring(3, 1) while using substring to index greater than from index
Study String Manipulation in Java

Split by first found String in Java

is ist possible to tell String.split("(") function that it has to split only by the first found string "("?
Example:
String test = "A*B(A+B)+A*(A+B)";
test.split("(") should result to ["A*B" ,"A+B)+A*(A+B)"]
test.split(")") should result to ["A*B(A+B" ,"+A*(A+B)"]
Yes, absolutely:
test.split("\\(", 2);
As the documentation for String.split(String,int) explains:
The limit parameter controls the number of times the
pattern is applied and therefore affects the length of the resulting
array. If the limit n is greater than zero then the pattern
will be applied at most n - 1 times, the array's
length will be no greater than n, and the array's last entry
will contain all input beyond the last matched delimiter.
test.split("\\(",2);
See javadoc for more info
EDIT: Escaped bracket, as per #Pedro's comment below.
Try with this solution, it's generic, faster and simpler than using a regular expression:
public static String[] splitOnFirst(String str, char c) {
int idx = str.indexOf(c);
String head = str.substring(0, idx);
String tail = str.substring(idx + 1);
return new String[] { head, tail} ;
}
Test it like this:
String test = "A*B(A+B)+A*(A+B)";
System.out.println(Arrays.toString(splitOnFirst(test, '(')));
System.out.println(Arrays.toString(splitOnFirst(test, ')')));

Categories