您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。