如何在Java中搜索键/值对的字符串 [英] How to search a string of key/value pairs in Java

查看:36
本文介绍了如何在Java中搜索键/值对的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样格式化的字符串:

I have a String that's formatted like this:

"key1 = value1; key2 = value2; key3 = value3"

任意数量的键/值对.

我需要检查某个键是否存在(假设它称为"specialkey").如果是这样,我想要与之关联的值.如果设置了多个特殊键",我只想要第一个.

I need to check that a certain key exists (let's say it's called "specialkey"). If it does, I want the value associated with it. If there are multiple "specialkey"s set, I only want the first one.

现在,我正在寻找"specialkey"的索引.我从该索引处开始获取一个子字符串,然后查找第一个 = 字符的索引.然后,我寻找第一个; 字符的索引.这两个索引之间的子字符串为我提供了与"specialkey"相关联的值.

Right now, I'm looking for the index of "specialkey". I take a substring starting at that index, then look for the index of the first = character. Then I look for the index of the first ; character. The substring between those two indices gives me the value associated with "specialkey".

这不是一个优雅的解决方案,确实让我感到困扰.查找与"specialkey"相对应的值的一种优雅方法是什么?

This is not an elegant solution, and it's really bothering me. What's an elegant way of finding the value that corresponds with "specialkey"?

推荐答案

使用

这将为您提供一个包含以下元素的数组 kvPairs :

This will give you an array kvPairs that contains these elements:

key1=value1
key2=value2
key3=value3

遍历并拆分它们:

for(String kvPair: kvPairs) {
   String[] kv = kvPair.split("=");
   String key = kv[0];
   String value = kv[1];

   // Now do with key whatever you want with key and value...
   if(key.equals("specialkey")) {
       // Do something with value if the key is "specialvalue"...
   }
}

这篇关于如何在Java中搜索键/值对的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆