C#面試題統計"0"字元數量,並將統計數字插入到字元中。要求:
輸入:
rnbakabnr/000000000/0c00000c0/p0p0p0p0p/000000000/000000000/P0P0P0P0P/0C00000C0/000000000/RNBAKABNR
輸出:
rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR
答案:
//遞迴演算法
private string ProssStr(string tempStr)
{
string tempAll = "";
int j0 = tempStr.IndexOf('0');
if (j0 > -1)
{
int j1 = 0;
for (int i = 0; i < tempStr.Length - j0; i++)
{
string k2 = tempStr.Substring(j0 + i, 1);
if (k2 == "0")
{
j1 = j1 + 1;
}
else
{
break;
}
}
string tempStr1 = tempStr.Remove(j0, j1).Insert(j0, j1.ToString());
tempAll = ProssStr(tempStr1);
}
else
{
tempAll = tempStr;
}
return tempAll;
}
調用:
string tempStrAll = "";
string s = "rnbakabnr/000000000/0c00000c0/p0p0p0p0p/000000000/000000000/P0P0P0P0P/0C00000C0/000000000/RNBAKABNR";//輸入
tempStrAll = ProssStr(s);//執行演算法
輸出到變數tempStrAll:
rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR