String字符串转成键值对形式存储于Map(拆分字段)

来源:互联网 发布:三国 知乎 编辑:程序博客网 时间:2024/06/05 04:18
  今天有个需求是将url里面的字段截取出来,因为里面字段的顺序有可能会改变,所以为了省事,将url里面的字段截取出来用键值对的形式存在map中。废话不多说,直接上代码,代码都很简单而且写了注释,虽然很简单也可能有人需要,所以写成一个帖子,勿喷。  布局很简单,就是一个textview用来显示
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <TextView         android:id="@+id/txt_stringToMap"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textSize="18sp"/></LinearLayout>

下面是Activity

package com.example.zhongzhihuaproject;import java.util.HashMap;import java.util.Map;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;/** * 将string的url字符串转换为map存储并取出来设值 * @author Administrator * */public class StringToMapActivity extends Activity {        String url = "http://www.baidu.com/book/novel?content=c_app&title=斗破苍穹&createtime=201604262247&type=玄幻&docid=2698548";    private Map<String, String> map;    @Override    protected void onCreate(Bundle savedInstanceState) {        // TODO Auto-generated method stub        super.onCreate(savedInstanceState);        setContentView(R.layout.string_to_map_layout);        TextView txt_stringToMap = (TextView) findViewById(R.id.txt_stringToMap);        String aa = url.substring(url.lastIndexOf("?")+1, url.length());//截取?之后的内容        String [] bb = aa.split("&");//将所有&符号截取出来变成一个数组        String cc = null;//获取每个&之内的内容        String [] dd = null;//获取每个=号的内容        String key = null;        String value = null;        map = new HashMap<String, String>();        for (int i = 0; i < bb.length; i++) {            cc = bb[i];//获取每个&的内容            dd = cc.split("=");//拆分=号            key = dd[0];//=号前面的值            value = dd[1];//=号后面的值            map.put(key, value);//将值放入map中        }        txt_stringToMap.setText("title="+map.get("title")+"\n"                +"createTime="+map.get("createTime")+"\n"                +"type="+map.get("type")+"\n"                +"docid="+map.get("docid"));    }}
0 0