简体   繁体   English

没有空格的Java字符串拆分

[英]Java string split without space

I'm trying to split some user input. 我正在尝试拆分一些用户输入。 The input is of the form a1 b2 c3 d4. 输入的形式为a1 b2 c3 d4。 For each input (eg; a1), how do I split it into 'a' and '1'? 对于每个输入(例如; a1),如何将其拆分为“a”和“1”?

I'm familiar with the string split function, but what do I specify as the delimiter or is this even possible? 我熟悉字符串拆分功能,但是我指定什么作为分隔符,或者甚至可以这样做?

Thanks. 谢谢。

You could use String#substring() 你可以使用String #substring()

String a1 = "a1"
String firstLetterStr = a1.substring(0,1);
String secondLetterStr = a1.substirng(1,a1.length());

Similarly, 同样的,

String c31 = "c31"
String firstLetterStr = c31.substring(0,1);
String secondLetterStr = c31.substirng(1,c31.length());

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 . 如果要一般性地拆分字符串(而不是尝试按其他答案计算字符数),您仍然可以使用String.split(),但必须使用正则表达式 (Note: This answer will work when you have strings like a1, a2, aaa333, etc.) (注意:当你有像a1,a2,aaa333等字符串时,这个答案会有用)

String ALPHA = "\p{Alpha}";
String NUMERIC = "\d";

String test1 = "a1";
String test2 = "aa22";

ArrayList<String> alpha = new ArrayList();
ArrayList<String> numeric = new ArrayList();

alpha.add(test1.split(ALPHA));
numeric.add(test1.split(NUMERIC));
alpha.add(test2.split(ALPHA));
numeric.add(test2.split(NUMERIC));

At this point, the alpha array will have the alpha parts of your strings and the numeric array will have the numeric parts. 此时,alpha数组将包含字符串的alpha部分,数字数组将包含数字部分。 (Note: I didn't actually compile this to test that it would work, but it should give you the basic idea.) (注意:我实际上没有编译它来测试它是否可行,但它应该给你基本的想法。)

这真的取决于你以后如何使用数据,但除了split("")或通过索引访问单个字符之外,另一种分割成单个字符的方法是toCharArray() - 它只是将字符串分解为数组人物......

是的,有可能,你可以使用split("");

后使用分割用户输入到个人令牌split(" ")则可以使用分割每个令牌插入字符split("")使用空字符串作为分隔符)。

将空格拆分为一个字符串数组,然后使用String.charAt(0)String.charAt(1)拉出单个字符

I would recommend just iterating over the characters in threes. 我建议只迭代三个角色。

for(int i = 0; i < str.length(); i += 3) {
     char theLetter = str.charAt(i);
     char theNumber = str.charAt(i + 1);
     // Do something
}

Edit: if it can be more than one letter or digit, use regular expressions: 编辑:如果它可以是多个字母或数字,请使用正则表达式:

([a-z]+)(\d+)

Information: http://www.regular-expressions.info/java.html 信息: http//www.regular-expressions.info/java.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM