如何在c++中的一串字符串中提取出两个括号中间的字符
时间: 2023-12-03 20:44:50 浏览: 71
可以使用以下步骤来提取出两个括号中间的字符:
1. 找到第一个左括号的位置。
2. 找到第一个右括号的位置,从第一个左括号的位置开始遍历字符串。
3. 从左括号的下一个位置开始,将字符逐一加入一个新的字符串中,直到遇到右括号为止。
以下是一个示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "This is a (sample) string (with multiple) sets of parentheses";
// 找到第一个左括号的位置
size_t leftPos = str.find_first_of("(");
// 找到第一个右括号的位置
size_t rightPos = str.find_first_of(")", leftPos);
// 提取括号中的字符
string subStr = str.substr(leftPos + 1, rightPos - leftPos - 1);
cout << subStr << endl;
return 0;
}
```
输出结果为:```sample```。
相关问题
c++提取括号内的多行字符串
可以使用正则表达式来匹配括号内的多行字符串,然后使用 C++ 中的正则表达式库 `std::regex` 进行实现。以下是一个简单的示例代码:
```cpp
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string input = "int main() {\n"
" std::string str = R\"(This is a\n"
" multi-line\n"
" string)\", another_str = \"This is not\";\n"
"}";
std::regex re(R"~(R"([^\\()]*)\([^()]*\)[^"]*")~"); // 匹配括号内的多行字符串
std::smatch match;
while (std::regex_search(input, match, re)) {
std::cout << "Match found: " << match[0] << std::endl;
input = match.suffix().str();
}
return 0;
}
```
输出结果为:
```
Match found: R"(This is a
multi-line
string)"
```
这里的正则表达式 `R"~(R"([^\\()]*)\([^()]*\)[^"]*")~"` 匹配了以 `R"` 开头、括号内包含任何非括号字符、后跟括号和双引号之间没有双引号的字符串。请注意,由于正则表达式中包含反斜杠 `\`,因此需要使用原始字符串字面值 `R"()"`。
C++如何判断字符串中左右括号是否配对
可以使用栈来判断字符串中左右括号是否配对。
具体思路如下:
1. 创建一个空栈。
2. 从字符串的左边开始遍历每个字符,如果是左括号,则将其压入栈中。
3. 如果是右括号,则检查栈是否为空,若为空,则说明右括号与左括号不配对,返回false;若不为空,则将栈顶的左括号弹出,与当前右括号进行匹配。如果匹配成功,则继续遍历字符串,如果匹配失败,则返回false。
4. 如果遍历完字符串后,栈为空,则说明所有左括号都有与之匹配的右括号,返回true;否则返回false。
下面是使用C语言实现的代码:
```c
#include <stdio.h>
#include <stdbool.h> // 使用bool类型
bool checkParentheses(char* str) {
char stack[100]; // 假设字符串不超过100个字符,栈大小为100
int top = -1; // 栈顶指针初始化为-1,表示栈为空
int i = 0; // 遍历字符串的下标
while (str[i] != '\0') { // 遍历字符串
if (str[i] == '(') { // 左括号入栈
stack[++top] = '(';
} else if (str[i] == ')') { // 右括号匹配
if (top < 0 || stack[top] != '(') { // 栈为空或栈顶不是左括号,匹配失败
return false;
} else { // 匹配成功,弹出栈顶的左括号
top--;
}
}
i++;
}
if (top < 0) { // 如果遍历完字符串后,栈为空,则说明所有左括号都有与之匹配的右括号
return true;
} else {
return false;
}
}
int main() {
char str[100]; // 定义一个字符数组,用于存储输入的字符串
gets(str); // 读入字符串
if (checkParentheses(str)) {
printf("The parentheses are matched!");
} else {
printf("The parentheses are not matched!");
}
return 0;
}
```
注意:上述代码中,使用了gets()函数读入字符串,但是gets()函数存在安全漏洞,建议使用更加安全的fgets()函数代替。同时,由于str是一个指向字符数组的指针,在函数checkParentheses中对str进行修改,因此需要将其声明为char*类型。