Below is a String and I want to get the bold id from it.
String s = "> Index1 is: 261 String is: href: https://www.clover.com/v3/merchants/4B8BF3Y5NJH7P/orders/K0AH5696MRG6J?access_token=4ffcfacefd3b2e9611a448da68fff91f, id: **K0AH5696MRG6J**, currency: USD, title: Greta , note: This is test ,";
int ind = s.indexOf("id:");
s = s.substring(ind,s.indexOf(","));
It gives an error index out of bound.
I know that error is there because in substring(int,int) the second parameter value is not correct.
I am trying to get the substring between id: and ,.
Any help
You are getting an IndexOutOfBoundsException because substring found that end index was less than the begin index.
Throws:
IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
Your initial indexOf call finds the id: properly, but the call to s.indexOf(",") finds the first , in the string, which happens to be before id:.
Use an overload of indexOf that takes a second argument - the index at which to starting looking.
s = s.substring(ind,s.indexOf(",", ind));
I suggest you use
s.indexOf(",", ind)
to get the comma which is after the id: rather than the first one in the String.
If you haven't read all the methods in String yet, I suggest you do as you will be using this class again, and again.
your "," index is before your "id:" index. You must search , after id
// Search id:
int ind = s.indexOf("id:");
// After that: search comma
int comma = s.indexOf(",", ind +1);
this explains this sort of problems:
How to use substring and indexOf for a String with repeating characters?
Related
I have string 1-12.32;2-100.00;3-82.32; From this I need to extract the numbers based on my passing position value. If I pass 3, I would need 82.32, similarly if I pass 2, i need 100.00. I build a function as like below but it is not working as expected. Could someone correct this/help on this?
function String res(String str, String pos){
String res=str.substring(str.indexOf(pos+"-")+2, str.indexOf(";",str.indexOf(pos)));
return res;
}
where str= 1-12.32;2-100.00;3-82.32;
pos=1 (or) 2 (or) 3
Your end index is incorrect. You should search for the index of the first ";" after the start index.
int begin = str.indexOf(pos+"-") + 2;
String res=str.substring(begin, str.indexOf(";",begin));
str.indexOf(";",str.indexOf(pos)) will give you the index of the first ";", since str.indexOf(pos) gives you the index of the first "2", which is the first "2" in "1-12.32;".
I am trying to get a range of chars found in another string using Java:
String input = "test test2 Test3";
String substring = "test2";
int diffStart = StringUtils.indexOf(input, substring);
int diffEnd = StringUtils.lastIndexOf(input, substring);
I want to get
diffStart = 5
diffEnd = 10
But I am getting
diffStart = 5
diffEnd = 5
Based on Apache's Commons lastIndexOf function it should work:
public static int lastIndexOf(CharSequence seq,
CharSequence searchSeq)
Finds the last index within a CharSequence, handling null. This method
uses String.lastIndexOf(String) if possible.
StringUtils.lastIndexOf("aabaabaa", "ab") = 4
What am I doing wrong?
you probably want
diffStart = String.valueOf(StringUtils.indexOf(strInputString02, strOutputDiff));
diffEnd = diffStart + strOutputDiff.length();
lastIndexOf finds the matching string, but the last instance of it.
E.g. ab1 ab2 ab3 ab4
lastindexof("ab") finds the 4th ab
indexof("ab") finds the 1st ab (position 0)
However, they always return the location of the first character.
If there is only one instance of a substring lastindexof and indexof will give the same index.
(To enhance your example more, you may also want to do some -1 checks in case the substring is not there at all)
String str = "Aardvark";
str.indexOf('a');
I was wondering what index str would return if it asked for a certain character and the string contained multiple of it. For example, aardvark: would the method return index 0, for the first instance it saw the char? There are 3 'a' chars in the word, so which would it return?
One additional question (couldn't fit it in the original question)
What is the difference between
str.indexOf('a');
and
str.indexOf("a");
I know the first is a char and the second is a String, but if str = "Aardvark", wouldn't the second statement return -1 or some sort of error, because "a" refers to a single-character String, not one char of a string?
I'm very sorry if this was unclear, I couldn't really think of a better way to pose my question. Thanks in advance!
indexOf() will return the index of the first occurrence of the string/char
like you say, one looks for a char and the other on a sub string. "a" will be found, as "a" is a substring of "Aardvark"
It would print the first occurence..
To get the second occurence you
would have to
fill in
indexOf(char c, int lookafterfirstindex);
indexOf can also take those two parameters instead of just the char.
Link to API Doc:
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String,%20int)
Here is a simple example:
String text = "abcd_a";
System.out.println("Index of a: "+ text.indexOf('a')); // Index of a: 0
System.out.println("Index of a: "+ text.indexOf("a")); // Index of a: 0
System.out.println("Index of b: "+ text.indexOf('b')); // Index of b: 1
System.out.println("Index of c: "+ text.indexOf('c')); // Index of c: 2
System.out.println("Index of z: "+ text.indexOf('z')); // Index of z: -1
simple index of:
indexOf(char/string) will always return the first index of the occurrence.
from index:
There is also indexOf(char/string, int fromIndex) - which will search from a given position in your string.
last index:
There is a lastIndexOf(char/string) - which will search last occurrence.
Regarding the char vs String, I would use char if I only need one char index lookup. The char will peform much faster than the String index-lookup-methods!!!
Java String Spec
I have a method which takes a string parameter and split the string by # and after splitting it prints the length of the array along with array elements. Below is my code
public void StringSplitTesting(String inputString) {
String tokenArray[] = inputString.split("#");
System.out.println("tokenArray length is " + tokenArray.length
+ " and array elements are " + Arrays.toString(tokenArray));
}
Case I : Now when my input is abc# the output is tokenArray length is 1 and array elements are [abc]
Case II : But when my input is #abc the output is tokenArray length is 2 and array elements are [, abc]
But I was expecting the same output for both the cases. What is the reason behind this implementation? Why split() method is behaving like this? Could someone give me proper explanation on this?
One aspect of the behavior of the one-argument split method can be surprising -- trailing nulls are discarded from the returned array.
Trailing empty strings are therefore not included in the resulting array.
To get a length of 2 for each case, you can pass in a negative second argument to the two-argument split method, which means that the length is unrestricted and no trailing empty strings are discarded.
Just take a look in the documentation:
Trailing empty strings are therefore not included in the resulting
array.
So in case 1, the output would be {"abc", ""} but Java cuts the trailing empty String.
If you don't want the trailing empty String to be discarded, you have to use split("#", -1).
The observed behavior is due to the inherently asymmetric nature of the substring() method in Java:
This is the core of the implementation of split():
while ((next = indexOf(ch, off)) != -1) {
if (!limited || list.size() < limit - 1) {
list.add(substring(off, next));
off = next + 1;
} else { // last one
//assert (list.size() == limit - 1);
list.add(substring(off, value.length));
off = value.length;
break;
}
}
The key to understanding the behavior of the above code is to understand the behavior of the substring() method:
From the Javadocs:
String java.lang.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.
Examples:
"hamburger".substring(4, 8) returns "urge" (not "urger")
"smiles".substring(1, 5) returns "mile" (not "miles")
Hope this helps.
I have a string and I want to use some formulas, in which there is a word that is going to be searched. Sometimes that word could be in different place, depending on the user. In order to make substrings work, I have to ensure that when it happens, the code still works.
String temp = s;//Temp is a long string text
String fehlerspeicher="fehlerspeicher";
if(temp.matches(".*"+fehlerspeicher+".*")){
// i have to find as an integer, how many LETTERS are used till this spesific word
}//to make changes in the following code
String temp1=temp.substring(0, 15000);//15000 is an example. it can be 5000 or 20000 sometimes. It splits the text up from 15000th letter.
String temp2=temp.substring(15000);// It'd be useful to use this integer in these 2 formulas.
temp2=temp2.replaceFirst("200", "20_");
temp=temp1+temp2;
So, could it be somehow implementable? Thanks.
Use indexOf:
public int indexOf(String str)
Returns the index within this string of the first occurrence of the
specified substring.
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#indexOf(java.lang.String)
So to get the index of "fehlerspeicher" you can use:
int index = temp.indexOf("fehlerspeicher");
So to get the position of the 'f' in 'fehlerspeicher' you can use:
String temp = "hellofehlerspecher"; //example temp string
int index = temp.indexOf("fehlerspeicher");
int fPos = index + 1; //fpos will equal 6.