Search code examples
javastringglobal-variablesindexofsubstr

Substring(int,int) in java to consider string


I might be finding the complicated way around for this,but this is how it goes: Got a string stored in a global variable: For eg: This is the result of JSON string after reading from the REST API call stored in a global variable: String Str= ["["b8f400be-b823-49c6-b0dd-5c97dc5d45e4"]"]

Now i need to split the string within the " " and the output should be only b8f400be-b823-49c6-b0dd-5c97dc5d45e4

I used substring,indexOf,lastIndexOf but unable to get a clear working solution in either case.What am i missing here?

str.substring(5, str.indexOf("\"", str.indexOf("\"") + 1))
 str.substring(5, str.substring.lastIndexOf("\"")-4);

Bumping into errors with the backslashes and double quotes,so used the \" method to extract the result but still does not work.

Since the parameters of substring only accepts (int,int) i am unable to provide a string there to retrieve,any help would be greatly appreciated


Solution

  • You are adding extra unnecessary logic. Its simply

    str.substring(5, str.lastIndexOf("\"")-3); or even

    str.substring(5, str.lastIndexOf("\\"));

    Also, here is how you properly assign/post a String variable - String str = "["[\"b8f400be-b823-49c6-b0dd-5c97dc5d45e4\"]"]"

    At least that is what I am assuming based off of you using 5 as the first index of your substring. I originally thought you meant String str = "[\"b8f400be-b823-49c6-b0dd-5c97dc5d45e4\"]" What you posted was an array containing a single String value.