如何提取字符串中嵌套括号内的内容?代码问题求助
Hey there! Let's tackle this nested bracket extraction problem together—sounds like you're already on the right track, so let's refine that approach and get your code working.
Nested brackets are classic stack territory because their "last opened, first closed" behavior perfectly matches the stack's LIFO (last-in-first-out) property. Here's the core logic you're probably thinking of, clarified:
- We use a stack to track the positions of opening brackets
(as we iterate through the string. - When we hit a closing bracket
), we pop the most recent opening bracket's position from the stack—this tells us exactly where the current bracket pair starts. - Extract the substring between those two positions (excluding the brackets themselves) and add it to your vector.
Step-by-Step Implementation
Let's turn that logic into working C++ code (since you mentioned a vector, I'm assuming C++—adjust if needed!) with error handling for edge cases like mismatched brackets:
#include <iostream> #include <vector> #include <stack> #include <string> using namespace std; vector<string> extractNestedBracketContent(const string& inputStr) { vector<string> extractedContents; stack<int> openBracketIndices; for (int idx = 0; idx < inputStr.size(); ++idx) { if (inputStr[idx] == '(') { // Record where this opening bracket is located openBracketIndices.push(idx); } else if (inputStr[idx] == ')') { if (!openBracketIndices.empty()) { // Get the position of the matching opening bracket int startPos = openBracketIndices.top(); openBracketIndices.pop(); // Extract content between the brackets (skip the brackets themselves) string content = inputStr.substr(startPos + 1, idx - startPos - 1); extractedContents.push_back(content); } else { cerr << "Oops! Unmatched closing bracket at index " << idx << endl; } } } // Check for unclosed opening brackets if (!openBracketIndices.empty()) { cerr << "Warning: " << openBracketIndices.size() << " unclosed opening bracket(s) left!" << endl; } return extractedContents; } int main() { // Test with a nested example string testString = "(Hello (World (Foo) Bar) Baz)"; vector<string> results = extractNestedBracketContent(testString); cout << "Extracted bracket contents (from innermost to outermost):" << endl; for (const auto& content : results) { cout << "- " << content << endl; } return 0; }
What This Code Does
For the test string (Hello (World (Foo) Bar) Baz), the output will be:
Extracted bracket contents (from innermost to outermost): - Foo - World (Foo) Bar - Hello (World (Foo) Bar) Baz
The stack ensures we handle nested pairs correctly—innermost brackets are processed first because they close first. If you want the order reversed (outermost first), just reverse the extractedContents vector before returning it.
Common Pitfalls Your Code Might Be Hitting
If your original code wasn't working, here are a few things to check:
- Not using a stack: If you tried to track brackets with a simple counter, you can't map closing brackets to their exact matching opening brackets (critical for nested structures).
- Incorrect substring calculation: Forgetting to add 1 to the start position or subtract 1 from the end position will include the brackets themselves in your extracted content.
- Ignoring mismatched brackets: Unclosed or extra closing brackets can cause crashes or incorrect outputs—adding the error checks above avoids that.
Quick Customization Tips
- If you need to group content by nesting level, modify the stack to store both the index and the level, then use a vector of vectors to organize results.
- If you're dealing with other bracket types (
[],{}), update the code to track which bracket type was opened and ensure the closing bracket matches.
内容的提问来源于stack exchange,提问作者Foxy

