Ele*_*ios 0 .net vb.net math numbers
基本上我需要计算一个字符串中的总体数量,这是为了显示一些信息,比如在一个RegularExpression应用程序中建议打开的子标记表达式的总数.
然后我需要计算关闭的"()"的总数,而不是"("和"总数")的总和.
例如在这个字符串中:
Hello (world)
Run Code Online (Sandbox Code Playgroud)
预期结果将是:1关闭
这里:
Hello (world) ((how are (you)?
Run Code Online (Sandbox Code Playgroud)
预期结果将是:2关闭,2打开
和这里:
Hello ) ( World?
Run Code Online (Sandbox Code Playgroud)
预期结果将是:2开放
只是请求可以给我一些想法,哪些可以改进计算方法?
我得到了"("和")"字符的总数,现在我不知道该怎么办.
更新:
我用这个字符串示例测试:
(((X)))
Run Code Online (Sandbox Code Playgroud)
但我得到4个未闭合,只有1个关闭,我正在使用此代码:
Public Function Replace_All_Characters_Except(ByVal str As String, _
ByVal chars As Char(), _
replaceWith As Char) As String
Dim temp_str As String = String.Empty
For Each c As Char In str
For Each cc As Char In chars
If c = cc Then temp_str &= cc
Next cc
Next c
Return temp_str
End Function
Dim Total_Parentheses As String = Replace_All_Characters_Except(TextBox_RegEx.Text, {"(", ")"}, String.Empty)
Dim Total_Unagrupated As Integer = Total_Parentheses.Replace("()", String.Empty).Length
Dim Total_Agrupated As Integer = (Total_Parentheses.Length - Total_Unagrupated) \ 2
MsgBox(Total_Parentheses)
MsgBox(Total_Unagrupated)
MsgBox(Total_Agrupated)
Run Code Online (Sandbox Code Playgroud)
我会在这里使用Stack
Stack<char> stack = new Stack<char>();
string input = @"Hello (world) ((how are (you)?";
//string input = "Hello ) ( World?";
int closed = 0;
int opened = 0;
foreach (var ch in input)
{
if (ch == '(')
stack.Push('#');
else if (ch == ')')
{
if (stack.Count == 0)
opened++;
else
{
closed++;
stack.Pop();
}
}
}
opened += stack.Count;
Console.WriteLine("Opened:{0} Closed:{1}", opened, closed);
Run Code Online (Sandbox Code Playgroud)
编辑
Dim stack As New Stack(Of Char)
Dim input As String = "Hello (world) ((how are (you)?"
'Dim input As String = "Hello ) ( World?"
Dim opened As Integer = 0
Dim closed As Integer = 0
For Each ch As Char In input
If ch = "(" Then
stack.Push("#")
ElseIf ch = ")" Then
If stack.Count = 0 Then
opened = opened + 1
Else
closed = closed + 1
stack.Pop()
End If
End If
Next
opened = opened + stack.Count
Console.WriteLine("Opened:{0} Closed:{1}", opened, closed)
Run Code Online (Sandbox Code Playgroud)