快速开贴揭帖,求一个简单的字符串处理算法
源字符串str1,str2
需要处理str2,将前面位数与内容与str1相同的省略掉
说不清楚看例子:
str1:ABCDE str2:ABXX -------需要XX,AB被省略了
str2:ABCDE str2:ABCX -------需要X,ABC被省略了
str1:ABCDE str2:XABXX -------需要XABXX,前面没有相同的内容,不省略
快速揭帖,尽量简单,最好一个句子就搞定
[解决办法]
一个句子搞不定
另外如果
str1:ABCDE str2:CDXX 是什么?
[解决办法]
string str1="ABCDE", str2="ABXX";
StringBuilder sb = new StringBuilder(str2);
int len = Math.Min(str1.Length, str2.Length);
for (int i = 0; i < len; i++)
{
if(str1[i].Equals(str2[i]))
{
sb.Remove(0, 1);
}
}
MessageBox.Show(sb.ToString());
[解决办法]
- C# code
protected void Page_Load(object sender, EventArgs e) { Response.Write(RemoveStr1("ABCDE", "ABXX") + "<BR>"); Response.Write(RemoveStr1("ABCDE", "ABCX") + "<BR>"); Response.Write(RemoveStr1("ABCDE", "XABXX") + "<BR>"); } private string RemoveStr1(string str1, string str2) { int str1Length = str1.Length; int str2Length = str2.Length; int forLength = (str1Length > str2Length) ? str2Length : str1Length; for (int i = 0; i < forLength; i++) { string str1Temp = str1.Substring(0, 1); string str2Temp = str2.Substring(0, 1); if (str1Temp == str2Temp) { str1 = str1.Substring(1, str1.Length - 1); str2 = str2.Substring(1, str2.Length - 1); } } return str2; }