英文:
How to process a line in Java?
问题
以下是翻译好的部分:
问题中所涉及的行的格式如下:
1:{O:{o1,巴西,F1,G2,E1},N:{n1,阿尔巴尼亚,D2,V2,R2,E1,A2}}
问题是,我使用了 split("","")
,然后我有两个字符串,我需要从每个字符串中创建一个具有所述属性的对象。我如何读取每个属性并在其相应的位置使用它们?
英文:
The format of line in question is:
1:{O:{o1,Brasil,F1,G2,E1},N:{n1,Albania,D2,V2,R2,E1,A2}}
The thing is, I use the split(",")
and I have two strings and from each of them I have to create an object with said attributes. How can I read each one of the attributes and use them in its corresponding place?
答案1
得分: 0
以下是您提供的内容的翻译部分:
为了实现这一点,我提供了两种特定的方法,除了这个特定的任务,它们还可以用于其他事情。
第一个方法是 bracketsMaxDepth() 方法,它返回特定嵌套括号的深度。支持的括号类型为 (), [], {}, <>
。您感兴趣的是花括号( { } )。
第二个方法是 getNestedBracketedGroups() 方法,它将解析括号字符串中嵌套括号组的内容(提取),并将这些组的内容返回到单维字符串数组中。支持的括号类型为 (), [], {}, <>
。您感兴趣的是花括号( { } )。
getNestedBracketedGroups() 方法内部使用了 bracketsMaxDepth() 方法。例如,要解析以下字符串:
String line = "1:{O:{o1,Brasil,F1,G2,E1}," +
"G:{g1,Germany,D2,V2,F1,G2,E1}," +
"N:{n1,Albania,D2,V2,R2,E1,A2}}";
我们可以这样做(我添加了一个额外的元素进行测试):
String line = "1:{O:{o1,Brasil,F1,G2,E1},G:{g1,Germany,D2,V2,F1,G2,E1},N:{n1,Albania,D2,V2,R2,E1,A2}}";
line = line.trim();
// 获取玩家编号
String player = line.substring(0, line.indexOf(":"));
// 玩家是一个整数表示的字符串吗?
if (!player.matches("\\d+")) {
// 不是的话...退出
return; // 或者使用您需要的其他退出机制。
}
int playerNumber = Integer.parseInt(player);
// 获取玩家的生物...
String[] playerCreatures = getNestedBracketedGroups(line, 1, "{}",
true)[0].split(",(?![^\\{\\}]*\\})");
// 显示生物数据
System.out.println("玩家 #" + playerNumber);
for (int i = 0; i < playerCreatures.length; i++) {
String creat = playerCreatures[i];
int creatureNumber = i + 1;
String creatureType= creat.substring(0, creat.indexOf(":"));
// 获取生物属性
String[] creatureAttributes = creat.substring((creatureType + ":").length() + 1,
creat.length() - 1).split("\\s{0,},\\s{0,}");
System.out.println("\t生物 #" + creatureNumber);
System.out.println("\t\t生物类型: " + creatureType);
for (int j = 0; j < creatureAttributes.length; j++) {
System.out.println("\t\t\t属性 #" + (j + 1) + ": " + creatureAttributes[j]);
}
}
在控制台窗口中解析的输出将如下所示:
玩家 #1
生物 #1
生物类型: O
属性 #1: o1
属性 #2: Brasil
属性 #3: F1
属性 #4: G2
属性 #5: E1
生物 #2
生物类型: G
属性 #1: g1
属性 #2: Germany
属性 #3: D2
属性 #4: V2
属性 #5: F1
属性 #6: G2
属性 #7: E1
生物 #3
生物类型: N
属性 #1: n1
属性 #2: Albania
属性 #3: D2
属性 #4: V2
属性 #5: R2
属性 #6: E1
属性 #7: A2
bracketsMaxDepth() 方法:
/**
* 该方法接受一个字符串并返回嵌套括号的最大深度。要检查深度的括号类型在 bracketType 参数中提供。<br><br>
*
* @param bracketedString (String) 要处理的字符串。<br>
*
* @param bracketType (String - 默认为 "()")可以提供一个开括号、闭括号,或者同时提供开括号和闭括号(无空格)。此方法将处理 4 种不同的括号类型之一,它们如下:<pre>
*
* () 圆括号 (默认)
* {} 花括号
* [] 方括号
* <> 尖括号</pre>
*
* @return (Integer) 提供的括号类型的最大深度。如果提供的字符串中没有所提供类型的括号,则返回 0。如果所提供类型的字符串内存在不平衡,返回 -1。对于每个开括号,必须有一个闭括号,反之亦然。
*/
public static int bracketsMaxDepth(String bracketedString, String... bracketType) {
// 方法实现,已略过...
}
getNestedBracketedGroups() 方法:
/**
* 该方法将解析括号字符串中嵌套括号组的内容(提取),并将这些组的内容返回到 1D 字符串数组中。
*
* @param bracketedString (String) 包含要解析的括号内容的字符串。<br>
*
* @param desiredDepth (Integer) 默认为 0(完整深度)。要从中检索括号内容的嵌套深度。<br>
* 如果所提供的括号深度比所提供的输入字符串中包含的深度更深,则会抛出 IllegalArgumentException 异常,说明情况如此。
*
* @param bracketType (String) 您必须提供要处理的括号类型。可以通过提供单个开括号或闭括号,或者同时提供开括号和闭括号来实现。例如,如果需要圆括号,则以下所有条
<details>
<summary>英文:</summary>
To do this I provide two specific methods which can be useful for other things other than this particular task.
The first method is the **bracketsMaxDepth()** method which returns the the depth of a particular nested bracket. Supported brackets are `(), [], {}, <>`. The brackets you're interest in are the curly braces ( **{ }** ).
The second method is the **getNestedBracketedGroups()** method which will parse out (retrieve) the contents of nested brackets groups within a bracketed string and return those group contents within a Single Dimensional (1D) String Array. Supported brackets are `(), [], {}, <>`. The brackets you're interest in are the curly braces ( **{ }** ).
The **bracketsMaxDepth()** method is used internally by the **getNestedBracketedGroups()** method. As an example, to parse out the the following string:
String line = "1:{O:{o1,Brasil,F1,G2,E1}," +
"G:{g1,Germany,D2,V2,F1,G2,E1}," +
"N:{n1,Albania,D2,V2,R2,E1,A2}}";
we might do something like this (I added an extra creature for testing):
String line = "1:{O:{o1,Brasil,F1,G2,E1},G:{g1,Germany,D2,V2,F1,G2,E1},N:{n1,Albania,D2,V2,R2,E1,A2}}";
line = line.trim();
// Get player Number
String player = line.substring(0, line.indexOf(":"));
// Is the player a string representation of a integer number?
if (!player.matches("\\d+")) {
// Nope...exit
return; // or whatever exit mechanism you need to use.
}
int playerNumber = Integer.parseInt(player);
// Get Player's Creatures...
String[] playerCreatures = getNestedBracketedGroups(line, 1, "{}",
true)[0].split(",(?![^\\{\\}]*\\})");
// Display creatures data
System.out.println("Creatures for Player #" + playerNumber);
for (int i = 0; i < playerCreatures.length; i++) {
String creat = playerCreatures[i];
int creatureNumber = i + 1;
String creatureType= creat.substring(0, creat.indexOf(":"));
// Get creature Attributes
String[] creatureAttributes = creat.substring((creatureType + ":").length() + 1,
creat.length() - 1).split("\\s{0,},\\s{0,}");
System.out.println("\tCreature #" + creatureNumber);
System.out.println("\t\tCreature Type: " + creatureType);
for (int j = 0; j < creatureAttributes.length; j++) {
System.out.println("\t\t\tAttribute #" + (j + 1) + ": " + creatureAttributes[j]);
}
}
The parsed output to Console Window would look like:
Creatures for Player #1
Creature #1
Creature Type: O
Attribute #1: o1
Attribute #2: Brasil
Attribute #3: F1
Attribute #4: G2
Attribute #5: E1
Creature #2
Creature Type: G
Attribute #1: g1
Attribute #2: Germany
Attribute #3: D2
Attribute #4: V2
Attribute #5: F1
Attribute #6: G2
Attribute #7: E1
Creature #3
Creature Type: N
Attribute #1: n1
Attribute #2: Albania
Attribute #3: D2
Attribute #4: V2
Attribute #5: R2
Attribute #6: E1
Attribute #7: A2
----------
> The **bracketsMaxDepth()** method:
/**
* This method takes a string and returns the maximum depth of nested
* brackets. The bracket type to check the depth for is supplied within the
* bracketType parameter.<br><br>
*
* @param bracketedString (String) The string to process.<br>
*
* @param bracketType (String - Default is "()") Either a open bracket,
* or a close bracket, or both open and closed
* brackets can be supplied (no white-spaces). This
* method will process any <b>one</b> of 4 different
* bracket types and they are as follows:<pre>
*
* () Parentheses (Default)
* {} Curly Braces
* [] Square Brackets
* &lt;&gt; Chevron Brackets</pre>
*
* @return (Integer) The maximum depth of the supplied bracket type. 0 is
* returned if there are no brackets of the type supplied within the
* supplied string. -1 is returned if there is an unbalance within
* the supplied string of the supplied bracket type. For every open
* bracket there must be a close bracket and visa versa.
*/
public static int bracketsMaxDepth(String bracketedString, String... bracketType) {
char open = '('; // Default
char close = ')'; // Default
if (bracketType.length > 0) {
String bType = Character.toString(bracketType[0].charAt(0));
switch (bType) {
case "(":
case ")":
open = '(';
close = ')';
break;
case "{":
case "}":
open = '{';
close = '}';
break;
case "[":
case "]":
open = '[';
close = ']';
break;
case "<":
case ">":
open = '<';
close = '>';
break;
default:
throw new IllegalArgumentException("\nbracketsMaxDepth() Method Error!\n"
+ "Unknown bracket type supplied (" + bType + ")!\n");
}
}
int current_max = 0; // current count
int max = 0; // overall maximum count
int n = bracketedString.length();
char[] c = bracketedString.toCharArray();
// Traverse the input string
for (int i = 0; i < n; i++) {
if (c[i] == open) {
current_max++;
// update max if required
if (current_max > max) {
max = current_max;
}
}
else if (c[i] == close) {
if (current_max > 0) {
current_max--;
}
else {
return -1;
}
}
}
// finally check for unbalanced string
if (current_max != 0) {
return -1;
}
return max;
}
----------
> The **getNestedBracketedGroups()** method:
/**
* This method will parse out (retrieve) the contents of nested brackets
* groups within a bracketed string and return those group contents within a
* 1D String Array. The best way to see how this works is by examples. Let's
* say we have the following bracketed string:
* <pre>
*
* String a = "1(2(3)(4))(5(6)(7))";</pre><br>
* <p>
* In the above string we can see that there are two instances of level 1
* bracketed groups which in each level 1 group nest two more level 2
* bracketed groups:
* <pre>
*
* Level 1 Level 2
* (2(3)(4)) (3) (4)
*
* ==================================
*
* Level 1 Level 2
* (5(6)(7)) (6) (7)</pre><br>
* <p>
* Bracketed groups: <b>(2(3)(4))</b> and <b>(5(6)(7))</b> are both
* considered to be at nest level 1 (level 1 is the outer most level). They
* are both individual groups because they both have their own set of outer
* brackets. Within each level 1 group we have two sets of level 2 bracketed
* groups (4 level 2 groups altogether) which consist of: <b>(3)</b> &
* <b>(4)</b> and <b>(6)</b> & <b>
* (7)</b>.<br><br>
* <p>
* This method also utilizes the TokenJar's StringUtils.BracketsMaxDepth()
* method.
*
* @param bracketedString (String) The string which contains bracketed
* content to parse.<br>
*
* @param desiredDepth (Integer) Default is 0 (full depth). The
* nested depth to retrieve bracketed content
* from.<br> If the bracket depth supplied is
* deeper than what is contained within the
* supplied input string then an <b>IllegalArgu-
* mentException</b> is thrown explaining as
* such.
*
* @param bracketType (String) You must supply the bracket type to
* process. This can be done by supplying either
* a single open or close bracket or both open
* and close brackets, for example, any one of
* the following are all acceptable entries if
* parentheses are required:<pre>
*
* "(" ")" "()" ")("</pre><br>
*
* Any one of four (4) bracket types can be supplied. The allowable Bracket
* Types are:
* <pre>
*
* () Parentheses
* {} Curly Braces
* [] Square Brackets
* &lt;&gt; Chevron Brackets</pre>
*
* @param removeOuterBrackets (Optional - Boolean - Default is false) By
* default the outer brackets for each found
* group are also attached to the returned
* results. If true is supplied to this optional
* parameter then the outer brackets are removed
* from the returned group results.<br>
*
* @return (1D String Array) The determined nested groups desired.<br>
*
* @throws IllegalArgumentException if a depth is supplied greater than the
* available bracketed depth contained
* within the supplied input string. This
* exception is also thrown if it is found
* that the supplied Bracket Type is
* unbalanced (open and closed braces are
* not properly paired) within the supplied
* input string.
*/
public static String[] getNestedBracketedGroups(String bracketedString, int desiredDepth,
String bracketType, boolean... removeOuterBrackets) {
boolean removeOuter = false;
if (removeOuterBrackets.length > 0) {
removeOuter = removeOuterBrackets[0];
}
int d = bracketsMaxDepth(bracketedString, bracketType);
if (desiredDepth == 0) {
//Default for this method is 0 (full depth).
desiredDepth = 1;
}
if (d == -1) {
// Throw Exception...
throw new IllegalArgumentException("\n\ngetNestedBracketedGroups() Method Error!\n"
+ "Brackets mismatch in supplied string!\n");
}
else if (d < desiredDepth) {
// Throw Another Exception...
throw new IllegalArgumentException("\n\ngetNestedBracketedGroups() Method Error!\n"
+ "Invalid Depth Supplied! Brackets within the supplied string go to a\n"
+ "maximum depth of (" + d + ") and therefore can not go to the supplied "
+ "depth\nof (" + desiredDepth + "). Change the desired depth.\n");
}
char open = '('; // Default
char close = ')'; // Default
String bType = Character.toString(bracketType.charAt(0));
switch (bType) {
case "(":
case ")":
open = '(';
close = ')';
break;
case "{":
case "}":
open = '{';
close = '}';
break;
case "[":
case "]":
open = '[';
close = ']';
break;
case "<":
case ">":
open = '<';
close = '>';
break;
default:
throw new IllegalArgumentException("\ngetNestedBracketedGroups() Method Error!\n"
+ "Unknown bracket type supplied (" + bType + ")!\n");
}
List<String> list = new ArrayList<>();
int n = bracketedString.length();
char[] c = bracketedString.toCharArray();
int depth = 0;
String strg = "";
for (int i = 0; i < n; i++) {
if (c[i] == open) {
depth++;
}
if ((depth >= desiredDepth)) {
if (c[i] == close) {
depth--;
}
strg += Character.toString(c[i]);
if (depth < desiredDepth) {
strg = strg.trim();
if (removeOuter) {
if (strg.startsWith(Character.toString(open))) {
strg = strg.substring(1);
}
if (strg.endsWith(Character.toString(close))) {
strg = strg.substring(0,
strg.lastIndexOf(Character.toString(close)));
}
}
list.add(strg);
strg = "";
}
continue;
}
if (c[i] == close) {
depth--;
}
if (!strg.equals("")) {
strg = strg.trim();
if (removeOuter) {
if (strg.startsWith(Character.toString(open))) {
strg = strg.substring(1);
}
if (strg.endsWith(Character.toString(close))) {
strg = strg.substring(0,
strg.lastIndexOf(Character.toString(close)));
}
}
list.add(strg);
strg = "";
}
}
if (!strg.equals("")) {
strg = strg.trim();
if (removeOuter) {
if (strg.startsWith(Character.toString(open))) {
strg = strg.substring(1);
}
if (strg.endsWith(Character.toString(close))) {
strg = strg.substring(0,
strg.lastIndexOf(Character.toString(close)));
}
}
list.add(strg); // + Character.toString(close));
}
// (red(blue))grey((orange)green)
return list.toArray(new String[list.size()]);
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论