日期:2014-05-19  浏览次数:20887 次

字符串操作问题!
如何把   E938403IDI20284I
转成       E938-403I-DI20-284I     就是在每四个字符后插入一个“-”?有什么简单一点的方法吗?

------解决方案--------------------
正则可以,不过估计更复杂。我帖给你:
首先写这个替换方法
public string CapText(Match m)
{
return m.Value + "- ";
}
然后试试这个正则
private void button3_Click(object sender, EventArgs e)
{
string strSrc = "E938403IDI20284I ";
string strRegex = @ "(\w{1,4}) ";
MatchEvaluator eval = new MatchEvaluator(CapText);
string strResult = Regex.Replace(strSrc, strRegex, eval);
strResult = strResult.Substring(0, strResult.Length - 1);
MessageBox.Show(strResult);
}
------解决方案--------------------
//正则这样是不是简单些

Console.WriteLine(
System.Text.RegularExpressions.Regex.Replace(
"E938403IDI20284I ", @ "(\w{4})\B ", "$1- "));
------解决方案--------------------
SplitString( "E938403IDI20284I ", "- ", new int[] {4, 4, 4, 4});

//-----------------------------

private string SplitString(string orgString, string splitter, params int[] lengths)
{
char[] chars = orgString.ToCharArray();
StringBuilder sb = new StringBuilder();
int index = 0;

for(int i = 0; i < lengths.Length; i++)
{
for(int j = 0; j < lengths[i]; j++)
{
sb.Append(chars[index + j]);
}

if(i < lengths.Length - 1)
{
sb.Append(splitter);
index += lengths[i];
}
}

return sb.ToString();
}
------解决方案--------------------
如果你字符串长度就是这样固定的话就很简单了:
String a = "E938403IDI20284I ";
for (int i = 0; i < a.Length; i++)
{
if (i % 5 == 0)
{
a=a.Insert(i, "- ");
}
}
Console.WriteLine(a.Substring(1,a.Length-1));
Console.Read();
------解决方案--------------------
string str = "E938403IDI20284I ";
string temp = " ";
int i = 1;
foreach(char x in str)
{
temp += x;
if (i % 4 == 0 && i != str.Length)
temp += "- ";
i++;
}
Console.WriteLine(temp);