如何拆分数组中的字符串

时间:2017-08-15 16:56:58

标签: java arrays

首先,我知道可能有重复但我不理解,所以请不要将其标记为副本!

我希望将数组中的字符串(见下文)拆分为字符:

原件:

String original = "0, 0, 0, 0 | 1, 1, 1, 1 | 2, 2, 2, 2"

数组:

String[] array2 = {"0, 0, 0, 0", "1, 1, 1, 1", "2, 2, 2, 2"}

我想要的结果:

String[] arrayprime = {"0", "0", "0", "0", "1", "1", "1", "1", "2", "2", "2", "2"}

你会怎么做?我想到了

String[] array2 = original.split("\\|");
String[] arrayprime = array2.split(", ");

但它似乎没有用(说"找不到符号")。

我应该将数组(array2)变成一个String(如果是这样,如何)?然后再分开?

3 个答案:

答案 0 :(得分:3)

看起来你要分开", "" | "

由于split支持正则表达式,因此可以将其写为

String[] array = yourText.split(", | \\| ");
//                                 ^-OR operator which creates 
//                                   alternation between ", " and " | "

答案 1 :(得分:2)

你可以使用character classes,在这种情况下不需要转义

    String original = "0, 0, 0, 0 | 1, 1, 1, 1 | 2, 2, 2, 2";
    String arr[]=original.split("[|,]");
    System.out.println(Arrays.toString(arr));

答案 2 :(得分:1)

您的错误就在这一行

putenv('GOOGLE_APPLICATION_CREDENTIALS=../platform-engineering.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(array("https://www.googleapis.com/auth/bigquery",
                        "https://www.googleapis.com/auth/cloud-platform",
                       "https://www.googleapis.com/auth/cloudplatform.read-only"
));


$http = $client->authorize();


$body = '{"dataSourceId": "adwords","destinationDatasetId": "adwords","displayName": "testing","params": {"customer_id": "42342423432"}, "dataRefreshWindowDays": 3,"disabled": false, "datasetRegion":"US"}';
$resp = $http->request("POST", "https://content-bigquerydatatransfer.googleapis.com/v1/projects/platform-engineering/transferConfigs", [
    'body' => $body,
    'headers' => array('content-type' => 'application/json')
]);
print_r($resp->getBody()->getContents());

您不能在数组上使用split方法。 Split方法是在String上。所以基本上你必须迭代curl -H "Content‐Type: application/json" -H "Authorization: Bearer MY_TOKEN" -d '{"dataSourceId": "adwords","destinationDatasetId": "adwords","displayName": "mauliktestng","params": {"customer_id": "4729344234"}}' https://bigquerydatatransfer.googleapis.com/v1/projects/platform-engineering/transferConfigs 并在每个String[] arrayprime = array2.split(" "); 上应用拆分。

或者只是使用正则表达式

array2

请注意,在使用此字符串后,您的字符串中将包含空格,因为您的初始字符串包含空格。请考虑修剪它们以获得所需的输出。