最新回應

  • re: 遮蔽與覆寫 to chingchan : 有時候相同的東西(方法)會整理放到父類別(base),然後讓子類....
  • by HOW
  • re: 遮蔽與覆寫 看到這裡還是不懂Override的作用...如果只要顯示子類別的方法,那為何要去繼承父類別? ....
  • by chingchan
  • re: [C#] Code 小技巧 to HOW ?™ : 數值函數幾乎總是比字符串函數更有效率。
  • by HOW ?™
  • re: [C#] Code 小技巧 同事提到,字串是否是空值,用String.Length > 0 效能會比較差,並不會比Stri....
  • by HOW ?™
  • re: [C#]字串 to HOW ?™ : 再補充String串接還有一個方法, ....
  • by HOW ?™
  • re: [C#]字串 補充: + 運算子會預先計算字串長度,判萬有都少記憶體需要配置(深入淺出c# p.741),....
  • by HOW ?™
  • re: [C#]ArrayList初始容量 謝謝Allen老師的提醒,和感謝小賤健講解, 使用ArrayList會將所有要加入的物件都轉....
  • by HOW ?™
  • re: [c#]Local Objects to sholfen : 謝謝您的提醒,看到您的提醒頓時間恍然大悟,自己犯了最基本的錯誤,而在....
  • by HOW ?™
  • re: [c#]Local Objects to 91 : 謝謝您的詳細的講解,Console.Writeline(string)裡面,已....
  • by HOW ?™
  • re: [c#]Local Objects to Bill Chung : 謝謝您提供的資訊與指導,變數在函式裡面為Local Objec....
  • by HOW ?™

[C#]字串更換

修改字串,有很多種方法,在HOW TO:修改字串內容 (C# 程式設計手冊)

裡面有一個範例,主要因為字串是不可變動,所以將字串放入可變動的字元陣列中,來做修改。

            string content = "this are test";
            char[] tmp = content.ToCharArray();
            int errorWordIndex = content.IndexOf("are");
            if (errorWordIndex == -1)
            {
                Console.WriteLine(content);
                return;
            }

            tmp[errorWordIndex++] = 'i';
            tmp[errorWordIndex++] = 's';
            tmp[errorWordIndex] = ' ';

            string newContent = new string(tmp);
            Console.WriteLine(newContent);

Output :

2012-05-04_233338

不過在這個方法中,我遇到一個問題,當變動字跟原先字的字數不一樣時,這樣就會多一個空白。

 

如果可以先將要變動的字串移除,在將更換的字串新增到同一個起始索引位置,一樣運用字串為字元集合的特性,再搭配String.Insert() ,String.Remove ()方法,

這邊一樣要注意到,方法的例外狀況,索引值不得小於零,索引值加移除字串長度不能超過原先字串的長度。

            string content = "this are test";
            string replaceWord = "are";
            string newWord = "is";
            string correctContent = string.Empty;

            int index = content.IndexOf(replaceWord);

            correctContent = content.Remove(index, replaceWord.Length);

            correctContent = correctContent.Insert(index, newWord);

            Console.WriteLine(correctContent);

Output :

2012-05-04_231731

 

在C#中,可以使用String.Replace()來替換字元或字串。

            string content = "this are test";
            string replaceWord = "are";
            string newWord = "is";
            string correctContent = content.Replace(replaceWord, newWord);
            Console.WriteLine(correctContent);

Output :

2012-05-04_231731

原先認為這應該不用做筆記,字串更換不就都是用String.Replace()這個方法,但這方法有一些需注意的地方。

            string content = "this are test";
            string replaceWord = string.Empty;
            string newWord = "is";
            string correctContent = content.Replace(replaceWord, newWord);
            Console.WriteLine(correctContent);

Output :

2012-05-04_234322

主要原因參考MSDN,開宗明義就講明,不能放入Null和空字串。

2012-05-04_234441

因此自己寫一個MyReplace,來處理這個問題,

        public static string MyReplace(this string vaule, string oldString, string newString)
        {
            if (string.IsNullOrEmpty(oldString))
                return vaule;
            else
                return vaule.Replace(oldString, newString);
        }

在vb中,還有提供不區分大小寫,但在c#中沒有此功能,因此多載上面的MyReplace。

這邊有幾種作法,

1.使用vb的函式庫

2.使用System.Text.RegularExpressions

3.自己打造一個

 

這邊使用RegularExpressions

        public static string MyReplace(this string vaule, string oldString, string newString, bool IgnoreCase)
        {
            if (IgnoreCase)
 	return Regex.Replace(vaule, oldString, newString, RegexOptions.IgnoreCase);
            else
   	return vaule.MyReplace(oldString, newString);
               
        }

接著將它合併與簡化。

        public static string MyReplace(this string vaule, string oldString, string newString, bool IgnoreCase = false)
        {
            if (string.IsNullOrEmpty(oldString) || IgnoreCase)
                return Regex.Replace(vaule, oldString, newString, RegexOptions.IgnoreCase);
            else
                return vaule.Replace(oldString, newString);
        }

 

結論:

在撰寫這篇筆記時,自己不斷問自己,為什麼不直接都用System.Text.RegularExpressions,似乎在資源與效能上有差異,因此在撰寫這個擴充方法時,為了就是殺雞不用牛刀,或許有更好的寫法,另外,在第一個範例,也充滿的懷疑,在msdn How to系列,有這樣的範例,應該有它的道理,因為真的不怎麼好用,只能推測,我功力又不到家了,不懂這樣寫法,或者這邊主要就是要再次提醒,字串的不可變動。

MSDN Library Reference :

String.Replace 方法

HOW TO:修改字串內容

Reference :

Strings.Replace 方法的注意事項

Replace 字串的幾種方法

忽略大小写

String Replace 不区分大小写的方法

高效的忽略大小写的字符串替换(Replace)函数


如文章有錯誤,煩請告知,新人發帖請多包涵

創用 CC 授權條款
 


關連文章

[c#]Local Objects

[c#]中英文對照

[C#]字串比較

[SQL]清除資料表

回應

  • # re: [C#]字串更換 by 阿尼

    我想您可能已經知道了,不過我還是提醒一下:Regex的Pattern用動態傳進來的會有風險,例如:

    string s = ".+bc".MyReplace(".+","a",true);
    

     

    2012/5/5 上午 01:33 | 回覆

  • # re: [C#]字串更換 by HOW ?™

    to 阿尼 :
    還真的遺忘了這部分,忘記正則表達式的主要功用,來個問號不就什麼都沒了....,金ㄟ害,謝謝您的提醒。

    2012/5/5 上午 03:32 | 回覆

登入後使用進階評論

Please add 2 and 7 and type the answer here: