Separating Numeric values from Text Values

时间秒杀一切 提交于 2019-12-11 22:19:51

问题


I am retrieving information from a REST API and it displays:

"Per 78g - Calories: 221kcal | Fat: 12.65g | Carbs: 16.20g | Protein: 10.88g"

I have imported the items into a ListView and when a user clicks an item I would like to string each numeric value individually like below without their text. Based on the example above:

String calories = 221;
String fat = 12.65;
String carbs = 16.20;
String protein = 10.88;

I got rid of the "Per 78g" with:

String sd = food.getString("food_description");
String[] row = sd.split("-");
tems.add(new Item(food.getString("food_name"), row[1]));

Which displays the following in each list item.

"Calories: 221kcal | Fat: 12.65g | Carbs: 16.20g | Protein: 10.88g"

When the User clicks on a list Item: How do I separate this properly and eliminate the text as well? Once I get the numeric values individually I would be fine.

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub

    String calories = adapter.getItem(arg2).getDescription();

    String[] calRow = calories.split("?|?");

    Toast.makeText(getActivity(), "" + calRow[1], Toast.LENGTH_LONG).show();

    mCallback.onFoodSelected(adapter.getItem(arg2).getTitle(), calRow[1]);
}

The API documentation is really bad and outdated. I am using it because it has great information. For everyone that believes this is bad practice this is the example return JSON:

{  
   "foods":{  
      "food":{  
         "food_description":"Per 342g - Calories: 835kcal | Fat: 32.28g | Carbs: 105.43g | Protein: 29.41g",
         "food_id":"4384",
         "food_name":"Plain French Toast",
         "food_type":"Generic",
         "food_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/french-toast-plain"
      },
      "max_results":"20",
      "page_number":"0",
      "total_results":"228"
   }
}

回答1:


Changing your JSON as follows, will make your job more easier:

{  
   "foods":{  
      "food":{  
         "food_description":{
            "Per" : "342g",
            "Calories": "835kcal",
            " Fat": "32.28g",
            "Carbs":" 105.43g",
            " Protein": "29.41g"
            },
         "food_id":"4384",
         "food_name":"Plain French Toast",
         "food_type":"Generic",
         "food_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/french-toast-plain"
      },
      "max_results":"20",
      "page_number":"0",
      "total_results":"228"
   }
}

I am assuming you know how to parse it.
And in case you are not able to change your json, try to use StringTokenizer or use String.split().



来源:https://stackoverflow.com/questions/26540541/separating-numeric-values-from-text-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!