解析字符串的有效方法
举例来说,您有一个具有键值的字符串,但它后面的变量可以更改 例如:
KEY1=variable1, KEY2=variable2, KEY3=variable3
我想知道提取变量 1、变量 2 和变量 3 的最佳方法是什么。如果我知道子字符串并每次都获取它们,那就太好了,但我不知道变量可以改变。注意按键不会改变
say for example you have a string that has key values but the variables after it can change
ex:
KEY1=variable1, KEY2=variable2, KEY3=variable3
What I want to know is what is the best way to extract variable1, variable2, and variable3. It would be nice if I knew the the substrings and got them each time, but I don't bc the variables can change. Note the keys do not change
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你可以试试这个:
You can try this:
Harry 解决方案的一个变体是处理值中 , 和 = 周围的空间。
印刷
A variation on Harry's solution which would handle space around the , and = in the value is.
prints
如果您想要超级高效,没有不必要的对象创建或逐个字符迭代,您可以使用
indexOf
,它比大型子字符串的逐个字符循环更高效。If you want to be super-efficient, no unnecessary object creation, or character by character iteration, you can use
indexOf
which is more efficient than character by character looping for large substrings.如果变量值不能包含逗号或空格,则可以简单地使用“,”作为分割标记将字符串分割成数组。然后,您可以进一步在等号上拆分每个键以检索键和值。
If you're variable values cannot contain commas or spaces, you could simply split the string into an array using the ", " as the split token. Then you could further split each key on the equal sign to retrieve both the key and the value.