Java字符串分割不带空格
我正在尝试拆分一些用户输入。输入的形式为 a1 b2 c3 d4。 对于每个输入(例如a1),如何将其拆分为“a”和“1”?
我熟悉字符串分割函数,但是我应该指定什么作为分隔符,或者这是否可能?
谢谢。
I'm trying to split some user input. The input is of the form a1 b2 c3 d4.
For each input (eg; a1), how do I split it into 'a' and '1'?
I'm familiar with the string split function, but what do I specify as the delimiter or is this even possible?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以使用 String#substring()
类似地,
You could use String#substring()
Similarly,
如果您想一般地拆分字符串(而不是尝试根据其他答案计算字符数),您仍然可以使用 String.split(),但必须使用 正则表达式。 (注意:当您有 a1、a2、aaa333 等字符串时,此答案将起作用)
此时,alpha 数组将包含字符串的 alpha 部分,而数字数组将包含数字部分。 (注意:我实际上并没有编译它来测试它是否有效,但它应该为您提供基本的想法。)
If you want to split the string generically (rather than trying to count characters per the other answers), you can still use String.split(), but you have to utilize regular expressions. (Note: This answer will work when you have strings like a1, a2, aaa333, etc.)
At this point, the alpha array will have the alpha parts of your strings and the numeric array will have the numeric parts. (Note: I didn't actually compile this to test that it would work, but it should give you the basic idea.)
这实际上取决于您之后将如何使用数据,但除了
split("")
或通过索引访问单个字符之外,另一种拆分为单个字符的方法是toCharArray()
——它只是将字符串分解成字符数组......it really depends how you're going to use the data afterwards, but besides
split("")
or accessing individual characters by index, one other way to split into individual character istoCharArray()
-- which just breaks the string into an array of characters...是的,有可能,您可以使用
split("");
Yes, it is possible, you can use
split("");
使用
split(" ")
将用户输入拆分为单个标记后,您可以使用split("")
将每个标记拆分为字符(使用空字符串作为分隔符) )。After you split user input into individual tokens using
split(" ")
, you can split each token into characters usingsplit("")
(using the empty string as the delimiter).将空间拆分为字符串数组,然后使用
String.charAt(0)
和String.charAt(1)
提取各个字符Split on space into an array of Strings, then pull the individual characters with
String.charAt(0)
andString.charAt(1)
我建议只对三个字符进行迭代。
编辑:如果它可以是多个字母或数字,请使用正则表达式:
信息:http:// www.regular-expressions.info/java.html
I would recommend just iterating over the characters in threes.
Edit: if it can be more than one letter or digit, use regular expressions:
Information: http://www.regular-expressions.info/java.html