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

本文提供了一个简单的示例,说明如何从URL字符串中提取字段,并将其以键值对的形式存储在Map中,便于后续操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  今天有个需求是将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"));

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值