今天面试有一道面试题没解出来,郁闷啊 唉。首先,你应该看到这样的3部分 123<em>abc 456<em>def 789。这三部分是用 </em> 分割的。剩下的一步,你自己想吧。 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 static string GetString(string source, int len) { string newSource = source.Replace("<em>", ""); newSource = newSource.Replace("</em>", ""); if (newSource.Length < len) { throw new Exception("要截取的长度超出了限制"); } int lastIndex = source.LastIndexOf("</em>"); string endValue = lastIndex < source.Length - 5 ? source.Substring(lastIndex + 5, source.Length - lastIndex - 5) : ""; StringBuilder sb = new StringBuilder(); MatchCollection maths = Regex.Matches(source, "(?<value>[^>]*)(?<em>[<][/]?em[>])"); for (int i = 0; i < maths.Count; i++) { string value = maths[i].Groups["value"].Value; string em = maths[i].Groups["em"].Value; if (value.Length <= len) { if (em == "</em>") { sb.AppendFormat("<em>{0}</em>", value); } else { sb.Append(value); } len -= value.Length; } else { sb.Append(value.Substring(0, len)); len -= value.Length; break; } } if (len > 0) { sb.Append(endValue.Substring(0, len)); } return sb.ToString(); }坐等更好的办法 正则写错了 改为(?<value>[^<]*)(?<em>[<][/]?em[>]) dataSet数据写入xml文件 <急>一个表中能设置两个主键吗? 为什么有的namespace会跨dll而存在? 操作数据库遇到的两个小问题 关于DataGridView绑定IList的问题 C#图像转化问题 C#基础问题 各位高手请进:如何用同步套接字的方法访问~~~~~~~ KOOXOO早期采集技术实现DEMO! (c#) 在深圳工作的朋友,大家都在这签个名及联系方式好吗?大家相互多多交流呀。 静态成员是线程安全吗? IF判断语句不进入 请求观看
static string GetString(string source, int len)
{
string newSource = source.Replace("<em>", "");
newSource = newSource.Replace("</em>", "");
if (newSource.Length < len)
{
throw new Exception("要截取的长度超出了限制");
}
int lastIndex = source.LastIndexOf("</em>");
string endValue = lastIndex < source.Length - 5 ? source.Substring(lastIndex + 5, source.Length - lastIndex - 5) : ""; StringBuilder sb = new StringBuilder();
MatchCollection maths = Regex.Matches(source, "(?<value>[^>]*)(?<em>[<][/]?em[>])"); for (int i = 0; i < maths.Count; i++)
{
string value = maths[i].Groups["value"].Value;
string em = maths[i].Groups["em"].Value;
if (value.Length <= len)
{
if (em == "</em>")
{
sb.AppendFormat("<em>{0}</em>", value);
}
else
{
sb.Append(value);
}
len -= value.Length;
}
else
{
sb.Append(value.Substring(0, len));
len -= value.Length;
break;
}
}
if (len > 0)
{
sb.Append(endValue.Substring(0, len));
} return sb.ToString();
}坐等更好的办法
正则写错了 改为(?<value>[^<]*)(?<em>[<][/]?em[>])