[英]c# replace each instance of a character selection in a string
我發現有很多類似的參考文獻,但似乎都不是我想要的,因此希望有人能提供幫助。
簡單來說,我想將用戶輸入的字符串(輸入到Winform輸入中),首先去除所有空格,然后用英國貨幣符號(£)替換任何“非法”字符列表。 要求使用輸入,但該流程生成的文件具有修改后的文件名。
我寫了一個函數(基於擴展方法),但沒有按預期工作:
public static class ExtensionMethods
{
public static string Replace(this string s, char[] separators, string newVal)
{
var temp = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
return String.Join(newVal, temp);
}
}
public static string RemoveUnwantedChars(string enteredName, char[] unwanted, string rChar)
{
return enteredName.Replace(unwanted, rChar);
}
在我的代碼中,我已經兩次調用:
char[] blank = { ' ' };
string ename = Utilities.RemoveUnwantedChars(this.txtTableName.Text, blank, string.Empty);
char[] unwanted = { '(', ')', '.', '%', '/', '&', '+' };
string fname = Utilities.RemoveUnwantedChars(ename, unwanted, "£");
如果我輸入的字符串至少包含一個空格,上面的所有字符以及其他一些字母(例如,“(GH)F16.5%MX / Y&1 + 1”),則會得到以下結果:
ename =“(GH)F16.5%MX / Y&1 + 1”-這是正確的,因為它已刪除了空格。
fname =“ GH£F16£5£MX£Y£1£1”-這不能正常工作,因為它沒有替換第一個字符而是將其刪除。
其余字符已正確替換。 僅當字符串中的“非法”字符之一位於字符串開頭時,如果我的字符串是“ G(H)F16.5%MX / Y&1 + 1”,我會正確獲得“ G£H£F16£ 5£MX£Y£1£1”。 它還用一個“£”替換多個“非法”字符,因此“ M()GX + .1”將變成“ M£GX£1”,但應為“ M££GX£1”。
我認為問題出在您的替換擴展名中。 您在這一行中分裂
var temp = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
您正在刪除導致意外結果的空條目。 使用此代替:
var temp = s.Split(separators, StringSplitOptions.None);
之所以出現此問題,是因為string.Join()
僅在子字符串之間放置分隔符-絕不會在開始處放置一個分隔符。
一種可能的解決方案是避免使用string.Join()
並改為這樣編寫Replace()
:
public static class ExtensionMethods
{
public static string Replace(this string s, char[] separators, string newVal)
{
var sb = new StringBuilder(s);
foreach (char ch in separators)
{
string target = new string(ch, 1);
sb.Replace(target, newVal);
}
return sb.ToString();
}
}
當您在Replace函數中使用split方法時,您將獲得以下字符串:GH,F16、5,MX,Y,1、1。將它們與newVal結合使用時,您將得到:GH + newVal + F16 + newVal + ...因此省略第一個替換的字符。
您可能需要一些特殊情況來檢查第一個字符是否為“非法”,並將newVal放在字符串的開頭。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.