本篇文章给大家分享的是有关DotNet的字符转义操作是怎样的,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
在项目中使用到字符的转义,现在提供一种字符转义和反转义的操作方法:
1.转义符操作:
/// <summary> /// 转义符操作 /// </summary> /// <param name="s"></param> /// <param name="charToEliminate"></param> /// <returns></returns> public static string EscapeChar(string s, char charToEliminate) { char escapeChar; char substituteChar; GetEscapeAndEncodingChars(charToEliminate, out escapeChar, out substituteChar); int i; for (i = 0; i < s.Length; i++) { if (s[i] == charToEliminate || s[i] == escapeChar) { break; } } if (i == s.Length) { return s; } var sb = new StringBuilder(s.Substring(0, i), s.Length + 16); for (; i < s.Length; i++) { var c = s[i]; if (c == charToEliminate) { sb.Append(escapeChar); sb.Append(substituteChar); } else if (c == escapeChar) { sb.Append(escapeChar, 2); } else { sb.Append(c); } } return sb.ToString(); }
2.反转义符操作:
/// <summary> /// 反转义符操作 /// </summary> /// <param name="s"></param> /// <param name="eliminatedChar"></param> /// <returns></returns> public static string UnescapeChar(string s, char eliminatedChar) { ArgumentValidator.ThrowIfNull(s, "s"); char escapeChar; char substituteChar; GetEscapeAndEncodingChars(eliminatedChar, out escapeChar, out substituteChar); if (-1 == s.IndexOf(escapeChar)) { return s; } var sb = new StringBuilder(s.Length); for (var i = 0; i < s.Length; i++) { var c = s[i]; var next = i + 1; if (c != escapeChar || next == s.Length) { sb.Append(c); continue; } if (s[next] == escapeChar) { sb.Append(escapeChar); i++; } else if (s[next] == substituteChar) { sb.Append(eliminatedChar); i++; } else { var msg = ("Invalid escaped string '{0}'. Position {1} has escape character, but it is not followed by " + "another escape character or by the substitute character").Fi(s, i); throw new AssertionViolationException(msg); } } return sb.ToString(); }
3.获取转义符和编码字符:
/// <summary> /// 获取转义符和编码字符 /// </summary> /// <param name="charToEliminate"></param> /// <param name="escapeChar"></param> /// <param name="encodingChar"></param> private static void GetEscapeAndEncodingChars(char charToEliminate, out char escapeChar, out char encodingChar) { var i = MEscapeChars[0] == charToEliminate ? 1 : 0; escapeChar = MEscapeChars[i]; i++; if (MEscapeChars[i] == charToEliminate) { i++; } encodingChar = MEscapeChars[i]; }
以上就是DotNet的字符转义操作是怎样的,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。