[英]Splitting a String by two things?
I have the following code:我有以下代码:
import java.util.Scanner;
public class Chapter11_ProjectPinochle {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
String a;
System.out.println("Type in your pinochle deals: ");
a=sc.nextLine();
sc.close();
String[] deals=a.split("");
}
}
I need to split the String I named "a"
into a 16 spaced array.我需要将我命名为
"a"
的字符串拆分为一个 16 间隔的数组。 But the problem with the splitting is that the input is something like this: ATKQQJ,AKQQ,KQQJN,A
.但是拆分的问题在于输入是这样的:
ATKQQJ,AKQQ,KQQJN,A
。 I need to split this into 16 parts and save it to an array I named "deals."
我需要将其拆分为 16 个部分并将其保存到我命名为
"deals."
的数组中"deals."
I've tried String[] deals=a.split("" && ",");
我试过
String[] deals=a.split("" && ",");
but apparently that isn't valid.但显然这是无效的。 I've also tried to split String a into 2 separate arrays and then put them together, but I realized I didn't know how.
我还尝试将 String a 拆分为 2 个单独的数组,然后将它们放在一起,但我意识到我不知道如何做。 I want the output to be
["A","T","K","Q","Q","J","A","K","Q","Q","K","Q","Q","J","N","A"]
when the input is: ATKQQJ,AKQQ,KQQJN,A
.我希望输出是
["A","T","K","Q","Q","J","A","K","Q","Q","K","Q","Q","J","N","A"]
当输入为: ATKQQJ,AKQQ,KQQJN,A
。 How should I accomplish this?我应该如何做到这一点?
//Split it out into individual characters
System.out.println(Arrays.toString("ATKQQJ,AKQQ,KQQJN,A".replace(",", "").toCharArray()));
//Split it into strings of a single character
System.out.println(Arrays.toString("ATKQQJ,AKQQ,KQQJN,A".replace(",", "").split("")));
Here you go:干得好:
String a = "ATKQQJ,AKQQ,KQQJN,A";
// Split the string into comma-separated parts
String[] parts = a.split(",");
//Join those parts into a single string
String whole = String.join("",parts);
//Finally, split it up into individual letters
String[] letters = whole.split("");
Could have also generated whole
by removing the commas from a
.也已经产生
whole
通过删除逗号a
。
Try this code试试这个代码
import java.util.Scanner;
public class Chapter11_ProjectPinochle {
public static void main(String[]args) {
Scanner sc = new Scanner(System.in);
String a,b="";
System.out.println("Type in your pinochle deals: ");
a = sc.nextLine();
sc.close();
String[] temp = a.split(",");
for (int i=0; i<temp.length; i++){
for (int j=0; j<temp[i].length(); j++){
b+=temp[i].charAt(j);
}
}
char[] deals=new char[b.length()];
for (int i=0; i<b.length(); i++){
deals[i]=b.charAt(i);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.