[英]Get correct string position C#
I have a string: 我有一个字符串:
string str = "Wishing you {all a great} day {ahead}. \n Thanks a lot \n } \n for {your} help!}"
I read the string line by line. 我逐行阅读字符串。 So at present I have 4 lines with me:
所以目前我有4行:
1. Wishing you {all a great} day {ahead}.
2. Thanks a lot
3. }
4. for {your} help!}
The intention is to check whether "}" is the closing brace of the string and that it should not appear as a single character in any of the other lines. 目的是检查“}”是否为字符串的右大括号,并且不应在其他任何行中将其显示为单个字符。
My approach is this: 我的方法是这样的:
In the above string, I want to get the position of the "}" in the main string. 在上面的字符串中,我想获取“}”在主字符串中的位置。 And then check whether there are characters after that position to check whether its the closing brace.
然后检查该位置之后是否有字符,以检查其右大括号。
But Iam unable to get the correct position of "}" as it may appear in other lines as well. 但是Iam无法获得“}”的正确位置,因为它也可能出现在其他行中。
Is there any better way to go about this? 有没有更好的方法来解决这个问题?
Within a single string, it sounds like you should iterate over the characters in the string and keep a count of how many opening and how many closing braces you've seen. 在单个字符串中,听起来您应该遍历字符串中的字符,并计算已看到的多少个开括号和多少个大括号。 Something like this:
像这样:
int open = 0;
for (int i = 0; i < text.Length; i++)
{
switch (text[i])
{
case '{':
open++;
break;
case '}':
if (open > 0)
{
open--; // Matches an opening brace
}
else
{
// Whatever you want to do for an unmatched brace
}
break;
default: // Do nothing
break;
}
}
If you need to know where the opening brace was, you might want a Stack<int>
instead of just a count. 如果您需要知道开括号在哪里 ,则可能需要一个
Stack<int>
而不是一个计数。 Then when you see a {
you push the index ( i
) onto the stack. 然后,当看到
{
,将索引( i
)压入堆栈。 When you see a }
, if the stack isn't empty you pop it to find the matching opening brace. 当看到
}
,如果堆栈不为空,则将其弹出以找到匹配的左括号。
Next you need to consider whether you ever need to escape the braces to remove their "special" meaning... at which point things become more complicated again. 接下来,您需要考虑是否需要转义括号以消除其“特殊”含义……在这一点上,事情又变得更加复杂了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.