有一字符串格式如下:(A(B)(C(D)(E))F) 字符串中的括號成對出現,寫一java函數取出第N(以左括號出現的順序來索引)對括號裏的內容。
public class Csdn1 {
public static void main(String[] args) {
String str = "(A(B)(C(D)(E))F)";
System.out.println(getContent(5, str));
}
public static String getContent(int n, String str) {
int start = -1, end = 0;
char[] arr = str.toCharArray();
int count = 0, j = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == '(') {
count++;
if (count == n) {
start = i;//找到,記錄開始位置
j = 0; // 開始位置重置
}
if (i >= start) {
j++; // 左( ++
}
}
if (arr[i] == ')') {
if (i >= start) { //有開始位置纔開始匹配結束
j--; // 右( --
}
if (j == 0) { //左右括號匹配完成後記錄結束位置並跳出循環
if (start == -1) {
System.out.println("第" + n + "個元素不存在!");
} else {
end = i + 1;
return str.substring(start, end);
}
}
}
}
return "";
}
}