Java 字符串解析 - {k1=v1,k2=v2,...}
我有以下字符串,可能包含 ~100 个条目:
String foo = "{k1=v1,k2=v2,...}"
并且我希望编写以下函数:
String getValue(String key){
// return the value associated with this key
}
我想在不使用任何解析库的情况下执行此操作。有什么快速的想法吗?
I have the following string which will probably contain ~100 entries:
String foo = "{k1=v1,k2=v2,...}"
and am looking to write the following function:
String getValue(String key){
// return the value associated with this key
}
I would like to do this without using any parsing library. Any ideas for something speedy?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果您知道您的字符串总是这样,请尝试以下操作:
警告:我实际上并没有尝试过这个;可能会有轻微的语法错误,但逻辑应该是合理的。请注意,我还进行了完全零错误检查,因此您可能想让我所做的更加稳健。
If you know your string will always look like this, try something like:
Warning: I didn't actually try this; there might be minor syntax errors but the logic should be sound. Note that I also did exactly zero error checking, so you might want to make what I did more robust.
我能想到的最快但最丑陋的答案是使用状态机逐个字符地解析它。它非常快,但非常具体且相当复杂。在我看来,您可能有几种状态:
示例:
此外,您可以使用 StringTokenizers(速度较快)或 Regex(速度较慢)更快地实现此目的。但总的来说,单个字符解析很可能是最快的方法。
The speediest, but ugliest answer I can think of is parsing it character by character using a state machine. It's very fast, but very specific and quite complex. The way I see it, you could have several states:
Example:
In addition, you can implement this a lot faster using StringTokenizers (which are fast) or Regexs (which are slower). But overall, individual character parsing is most likely the fastest way.
如果字符串有很多条目,您可能最好在不使用 StringTokenizer 的情况下手动解析以节省一些内存(如果您必须解析数千个这些字符串,则值得额外的代码):
我使用这些字符串测试了此代码,它工作正常:
{k1=v1}
{k1=v1, k2 = v2, k3= v3,k4 =v4}
{k1= v1,}
If the string has many entries you might be better off parsing manually without a StringTokenizer to save some memory (in case you have to parse thousands of these strings, it's worth the extra code):
I tested this code with these strings and it works fine:
{k1=v1}
{k1=v1, k2 = v2, k3= v3,k4 =v4}
{k1= v1,}
未经测试就写的:
是的,它很丑:-)
Written without testing:
Yes, it's ugly :-)
好吧,假设值中没有“=”或“,”,最简单(且破旧)的方法是:
是的,不推荐:)
Well, assuming no '=' nor ',' in values, the simplest (and shabby) method is:
Yeah, not recommended :)
添加代码来检查
foo
中是否存在key
留给读者作为练习:-)Adding code to check for existance of
key
infoo
is left as exercise to the reader :-)请找到我的解决方案:
用法
Please find my solution:
Usage