如何使用替换、子字符串、拆分等执行字符串操作
How to perform string manipulation using replace, substring, split, etc
我有这样的字符串数据
string1 = ["car","house","boat"]["one","two","three","four"]["tiger","cat"]
我希望输出是这样的:
first : car,house,boat
second : one,two,three,four
third : tiger,cat
我应该如何对该字符串进行操作?
这是我目前的尝试:
result6 = string1.substring(1);
String[] parts = result6.split("\[");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
result3 = part1.replaceAll("[^a-zA-Z0-9,]", "");
result4 = part2.replaceAll("[^a-zA-Z0-9,]", "");
result5 = part3.replaceAll("[^a-zA-Z0-9,]", "");
result1 = "first : " + part1 + "\n" + "second : " + part2 + "\n" + "third : \n" + part3;
但这让我得到了错误的输出。
您在 result1
赋值部分添加了 part1
、part2
、part3
而不是 result3
、4、5。而且我建议你根据 ][
进行拆分,如果你只根据 [
进行拆分,你会在 parts[0]
.
中得到一个空字符串
String string1 = "[\"car\",\"house\",\"boat\"][\"one\",\"two\",\"three\",\"four\"][\"tiger\",\"cat\"]";
String parts[] = string1.split("\]\[");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
String result3 = part1.replaceAll("[^a-zA-Z0-9,]", "");
String result4 = part2.replaceAll("[^a-zA-Z0-9,]", "");
String result5 = part3.replaceAll("[^a-zA-Z0-9,]", "");
String result1 = "first : " + result3 + "\n" + "second : " + result4 + "\n" + "third : " + result5;
System.out.println(result1);
输出:
first : car,house,boat
second : one,two,three,four
third : tiger,cat
我有这样的字符串数据
string1 = ["car","house","boat"]["one","two","three","four"]["tiger","cat"]
我希望输出是这样的:
first : car,house,boat
second : one,two,three,four
third : tiger,cat
我应该如何对该字符串进行操作?
这是我目前的尝试:
result6 = string1.substring(1);
String[] parts = result6.split("\[");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
result3 = part1.replaceAll("[^a-zA-Z0-9,]", "");
result4 = part2.replaceAll("[^a-zA-Z0-9,]", "");
result5 = part3.replaceAll("[^a-zA-Z0-9,]", "");
result1 = "first : " + part1 + "\n" + "second : " + part2 + "\n" + "third : \n" + part3;
但这让我得到了错误的输出。
您在 result1
赋值部分添加了 part1
、part2
、part3
而不是 result3
、4、5。而且我建议你根据 ][
进行拆分,如果你只根据 [
进行拆分,你会在 parts[0]
.
String string1 = "[\"car\",\"house\",\"boat\"][\"one\",\"two\",\"three\",\"four\"][\"tiger\",\"cat\"]";
String parts[] = string1.split("\]\[");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
String result3 = part1.replaceAll("[^a-zA-Z0-9,]", "");
String result4 = part2.replaceAll("[^a-zA-Z0-9,]", "");
String result5 = part3.replaceAll("[^a-zA-Z0-9,]", "");
String result1 = "first : " + result3 + "\n" + "second : " + result4 + "\n" + "third : " + result5;
System.out.println(result1);
输出:
first : car,house,boat
second : one,two,three,four
third : tiger,cat