java 切断字符串中的特定部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13109564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cut off a specific part in a String
提问by Xitrum
For examples, I have:
例如,我有:
String s = "{\"ABC\"}:Mycontent{\"123\"}";
I only want to get the Mycontent{"123"} part and this part can be changed dynamically. Can anybody please show me how to do it (Fast performance)?
我只想获得 Mycontent{"123"} 部分,这部分可以动态更改。任何人都可以告诉我怎么做(快速性能)?
回答by John Demetriou
Split method inside string can split a string around matches of regular expression so you can use this method. You can also use subsequence method if the position of the string you want is always the same. Also you can use the substring method. Many ways. Personal favorite is substring
字符串中的拆分方法可以围绕正则表达式的匹配项拆分字符串,因此您可以使用此方法。如果您想要的字符串的位置始终相同,您也可以使用 subsequence 方法。您也可以使用子字符串方法。很多种方法。个人最喜欢的是子串
str2=str.substring(begin, [end])
I put [] around end because it is not necessary. If you do not put an end index the substring will continue until the end of the string. Both indexes must be integers. Also this method returns a string.
我把 [] 放在 end 周围,因为它没有必要。如果您不放置结束索引,则子字符串将一直持续到字符串的结尾。两个索引都必须是整数。此方法也返回一个字符串。
If the size of the number changes dynamically aswell (e.g. 123 turns to 4567) you can solve this by not using an end index then using a find function and finding the character that comes after the last digit in your string (I suppose this does not change) and then replacing that character (using a replace method) with a \0 so the string ends there.
如果数字的大小也动态变化(例如 123 变为 4567),您可以通过不使用结束索引然后使用查找函数并查找字符串中最后一位数字之后的字符来解决此问题(我想这不会更改),然后用 \0 替换该字符(使用替换方法),以便字符串在那里结束。
All the methods I have mentioned and there explanations can be found in javadoc
我提到的所有方法和解释都可以在javadoc 中找到
回答by Vikdor
Using indexOf on the string, you can find the occurrence of ':' and get the substring from there as follows:
在字符串上使用 indexOf,您可以找到 ':' 的出现并从那里获取子字符串,如下所示:
s.substring(s.indexOf(':') + 1)
If this is a structured output from an upstream system, you should look for standard way to interpret it (at first look, it appeared like JSON which means you should use a JSON parser. But it seems to be something else, you would know better about the source of this input).
如果这是来自上游系统的结构化输出,您应该寻找标准方式来解释它(乍一看,它看起来像 JSON,这意味着您应该使用 JSON 解析器。但它似乎是别的东西,你会更清楚关于此输入的来源)。