之前版本:
新版本:
/// <summary>
/// 记录代码中的括号,尖括号,方括号,大括号的配对位置,注释中的不记录。
/// </summary>
/// <param name="sText"></param>
/// <param name="C_ExplanatoryNote_Pos">注释位置</param>
/// <returns></returns>
/// 创建时间: 2022-08-26 最后一次修改时间:2022-10-01
public static DList_<Pair_<int, int>> _Syntax_C_FindBrackets(this string sText)
{
//注释用空格代替
string sReplace = sText._Syntax_C_Replace_ExplanatoryNote();
//找出所有的 (, <, [,{ 然后配对
string sLeft = "(<[{";
DList_<Pair_<int, int>> dLeft = new DList_<Pair_<int, int>>();
for (int i = 0; i < sReplace.Length; ++i)
{
char cLeft = sReplace[i];
if(sLeft.IndexOf(cLeft) != -1)
{
dLeft.Add(new Pair_<int, int>(i, -1));
}
}
//查找配对
DListNote_<Pair_<int, int>> pNote = dLeft.First;
while (pNote != null)
{
Pair_<int, int> p = pNote.Data;
p.Second = _Syntax_C_NextBrackets(sReplace, p.First);
pNote = pNote.Next;
}
DList_<Pair_<int, int>> dResult = new DList_<Pair_<int, int>>();
pNote = dLeft.First;
while (pNote != null)
{
Pair_<int, int> p = pNote.Data;
if (p.Second != -1)
dResult.Add(p);
pNote = pNote.Next;
}
return dResult;
}
/// <summary>
/// 把C++代码中的注释用空格代替
/// </summary>
/// <param name="sText"></param>
/// <returns></returns>
/// 创建时间: 2022-09-01 最后一次修改时间:2022-09-01
public static string _Syntax_C_Replace_ExplanatoryNote(this string sText)
{
StringBuilder sb = new StringBuilder(sText.Length);
DList_<Pair_<int, int>> enp = _Syntax_C_ExplanatoryNote_Pos(sText);
for(int i = 0; i < sText.Length; ++i)
{
Boolean bFind = false;
foreach (Pair_<int, int> p in enp)
{
if( i >= p.First && i <= p.First + p.Second) //p.Second 是长度
{
bFind = true;
break;
}
}
if (bFind)
sb.Append(' ');
else
sb.Append(sText[i]);
}
return sb.ToString();
}
/// <summary>
/// 记录注释的位置和长度
/// </summary>
/// <param name="sText"></param>
/// <returns></returns>
/// 创建时间: 2022-08-26 最后一次修改时间:2022-08-26
public static DList_<Pair_<int,int>> _Syntax_C_ExplanatoryNote_Pos(this string sText)
{
DList_<Pair_<int, int>> dResult = new DList_<Pair_<int, int>>();
for (int i = 0; i < sText.Length; ++i)
{
if (sText[i] == '/')
{
if (i + 1 < sText.Length)
{
if (sText[i + 1] == '/')
{
int nStart = i;
i = sText.IndexOf('\n', i + 1);
if (i == -1)
{
dResult.Add(new Pair_<int, int>(nStart, sText.Length - i));
break;
}
else
{
dResult.Add(new Pair_<int, int>(nStart, i - nStart));
}
}
else if (sText[i + 1] == '*')
{
int nStart = i;
i = sText.IndexOf("*/", i + 1);
if (i == -1)
{
dResult.Add(new Pair_<int, int>(nStart, sText.Length - i));
break;
}
else
{
dResult.Add(new Pair_<int, int>(nStart, i - nStart + 2));
}
}
}
}
}
return dResult;
}