FigureCodeOut
FigureCodeOut

Reputation: 79

Retrieve data from a String

I have this String which is coming from form:

   String tmp = "Reason: decision=deny&denyReason=1&denyReasonSubcategory=PoorQuality&subCategoryComments=testsubCategoryComments=subCategoryComments=denyReasonSubcategory=ReviewAgainsubCategoryComments=hellosubCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryComments=subCategoryCommen=&subCategoryComments=&subCategoryComments=&subCategoryComments=&subCategoryComments=";

From the above string I need to retrieve:

 denyReason=1
 denyReasonSubcategory=PoorQuality  subCategoryComments=test
 denyReasonSubcategory=ReviewAgain   subCategoryComments=hello

I need to save them as below:

deny Reason in an array, so i can find corresponding value.

Rest as: Poor Quality :test; Review Again:hello

I have tried following:

          for (String word : tmp.split("\\&+")){
           if (word.contains("declineReason")){
                System.out.println(word.indexOf("declineReason"));
            // coming as 0
           }
          if (word.contains("declineReasonSubcategory")){
                System.out.println("helloo");
          }
          if (word.contains("subCategoryComments")){
                System.out.println("hii");
          } 
         }
        }

Honestly, it's been long since I work on string like this and just little lost on how to get the data.

Upvotes: 0

Views: 53

Answers (1)

Cheng Thao
Cheng Thao

Reputation: 1493

I would use a Scanner to extract the values.
One scanner to extract the pairs. Another scanner to extract the values of the pair.

See:

import java.util.*;
public class Main{
    public static void main(String[] args) {
      String tmp = "Reason: decision=deny&denyReason=1&denyReasonSubcategory=PoorQuality&subCategoryComments=testsubCategory";
      Scanner s = new Scanner(tmp).useDelimiter("\\&");
      while(s.hasNext()){
         Scanner s2 = new Scanner(s.next()).useDelimiter("=");
         System.out.println(s2.next() + ":" + s2.next());
      }
    }
}

Upvotes: 1

Related Questions