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;".
Related
Suppose I've the string
String path = "the/quick/brown/fox/jumped/over/the/lazy/dog/";
I would like the following output
String output = "the/quick/brown/fox/jumped/over/the/lazy/";
I was thinking the following would do
output = path.substring(0, path.lastIndexOf("/", 1));
given how the doc says
Returns the index of the first (last) occurrence of the specified character, searching forward (backward) from the specified index.
but that doesn't seem to work.
Any help would be appreciated.
It seems like every single answer is assuming that you already know the input string and the exact position of the last occurrence of "/" in it, when that is usually not the case...
Here's a more general method to obtain the nth-last (second-last, third-last, etc.) occurrence of a character inside a string:
static int nthLastIndexOf(int nth, String ch, String string) {
if (nth <= 0) return string.length();
return nthLastIndexOf(--nth, ch, string.substring(0, string.lastIndexOf(ch)));
}
Usage:
String s = "the/quick/brown/fox/jumped/over/the/lazy/dog/";
System.out.println(s.substring(0, nthLastIndexOf(2, "/", s)+1)); // substring up to 2nd last included
System.out.println(s.substring(0, nthLastIndexOf(3, "/", s)+1)); // up to 3rd last inc.
System.out.println(s.substring(0, nthLastIndexOf(7, "/", s)+1)); // 7th last inc.
System.out.println(s.substring(0, nthLastIndexOf(2, "/", s))); // 2nd last, char itself excluded
Output:
the/quick/brown/fox/jumped/over/the/lazy/
the/quick/brown/fox/jumped/over/the/
the/quick/brown/
the/quick/brown/fox/jumped/over/the/lazy
This works, given path length >2
final String path = "the/quick/brown/fox/jumped/over/the/lazy/dog/";
final int secondLast = path.length()-2;
final String output = path.substring(0, path.lastIndexOf("/",secondLast)+1);
System.out.println(output);
The lastIndexOf method's second parameter specifies the maximum index upto where the method should search the string. This means, that in your case
path.lastIndexOf("/", 1)
returns the first index of "/" whose index is smaller than 1.
First of all, lastIndexOf will return an index, not a string. It also searches backwards from the specified index 1, so it will only look at everything before and including the character at index 1. This means that it only checks t and h. Expectedly, it finds nothing and returns -1.
You should just omit the second argument if you want to search the whole string.
In addition, to achieve your desired output string (I assume you want the last path component removed?), you can use replaceAll with a regex:
String output = path.replaceAll("[^/]+/$", "");
Using Apache Commons IO
String output = org.apache.commons.io.FilenameUtils.getPath(path);
Not using Apache
public static String removeLastPart(String str) {
int pos = str.length() - 1;
while (str.charAt(pos) != '/' || pos + 1 == str.length()) {
pos--;
}
return str.substring(0, pos + 1);
}
If you are dealing with paths and files why not use the built in classes? Something like below seems to me easier than string manipulation:
Path path = Paths.get("the/quick/brown/fox/jumped/over/the/lazy/dog/");
System.out.println(path.getParent());
// prints: the\quick\brown\fox\jumped\over\the\lazy
System.out.println(path.getParent().getParent());
// prints: the\quick\brown\fox\jumped\over\the
For example,
String key = "aaa/bbb/ccc/ddd" ;
and i need my result string as "ccc/ddd". which is, sub-string of second last index of "/", The following code helps ::
String key="aaa/bbb/ccc/ddd";
key=key.substring(key.substring(0, key.lastIndexOf("/")).lastIndexOf("/")+1);
The final value of key will be "ccc/ddd".
Here's an use case:
String url = "http://localhost:4000/app/getPTVars";
int secondLastIndexOf = url.substring(0, url.lastIndexOf('/')).lastIndexOf('/');
System.out.println(secondLastIndexOf);
System.out.println(url.substring(secondLastIndexOf, url.length()));
and the output:
21
/app/getPTVars
Try - 1 approach:
int j = path.lastIndexOf("/");
int i = path.lastIndexOf("/", j - 1); // the 2nd last index from the last index
String output = path.substring(0, i + 1); // inclusive
String path = "the/quick/brown/fox/jumped/over/the/lazy/dog/";
String output = path.substring(0, path.lastIndexOf("/",path.lastIndexOf("/")-1)+1);
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
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?
System.out.println(1+2+"3");
System.out.println("1"+2+3);
output:-
33
123
First case is understood but the second case is not clear.
If we are doing + operation in string then is works as append(concatenation).
So in your first case 1+2+"3" ... 1+2 =3 but when it perform 3+"3" java concate 3 into String 3 that is 33.
and in second example "1"+2+3 ... 2 is append into String "1" that results as 12 and then "12" + 3 so result is = 123.
if the left part is String then it would invoke + operation on string which is append(concatenation) , while in number it is summation
+ is right associative; "1"+2 results in "12", and adding 3 gives "123".
The evaluation happens left to right. First time a string is met all the succeeding values are implicitly cast to string before being added to the expression. So in the first case you have 1+2 = 3, then a string is met and 2 is appended to the string "3". Second case - the string "1" is met and then each int is cast to string before being added to the result accumulated so far.
If you add anything to a string, it will be a string so 1 + "2"(string) is "12"(string).
if you keep on adding to string, you will keep on getting strings "12"(string) + 33 is "1233"(string).
I think this better justify your question.
Thanks
Kapil Garg
well, mathematical expressions are scanned from right usually.
In first case, if you scan from right , u get two int operands(1 and 2) and u add it and it comes to be 3 as int when move on further you find one operand("3") is string so you concatenate it and it comes out to be 33.
In second case, if you scan from right u get one string operand("1") and you concatenate it with 2 so it comes out to be 12 as string, when you move on you find int(2), but this time your first operand(12) is string, so again you concatenate it and it comes out to be 123.
in first case 1+2+"3"
first 1+2 is added and appended with string so output is 33.
but in the second case: "1"+2+3
first string is appended with 2 so operation of "1"+2 is string, automatically last is ("12"+3) also string.
that is :
1st case:
numeric output + string = string
2nd case:
string + numeric = string
that is casting to parent class with lower/wrapper data types the final output would be parent class.