2014-01-29 65 views
3

我從另一個應用程序中獲取像"123456""abcdef""123abc"這樣的字符串。 我需要格式化字符串,如"123-456","abc-def","123-abc"。字符串的長度也可以變化,就像我們可以有一串長度爲30個字符的字符串一樣。如果選擇第三個位置,則應在每個第三個字符後插入連字符。如何將連字符添加到每個第n個位置的字符串?

例如:輸入「abcdxy123z」 輸出「abc-dxy-123-z」爲第3位。

如果我們選擇第二個位置,然後輸出將是

「AB-CD-XY-12-3z」

我試着用的String.Format(「{0:#### - #### - #### - ####}「,Convert.ToInt64(」1234567891234567「))但如果我得到一個字母數字字符串,它不起作用。

+2

您遇到什麼問題需要幫助? –

+4

那麼......每第三個角色? –

+4

歡迎來到StackOverflow。您需要向我們提供您想要實現的具體細節,並且如果可能的話,您已經嘗試過的代碼。你需要的東西很不清楚,因爲你給了我們3個例子 - 全部6個字符長度 - 告訴我們字符數量可能會有所不同,但不告訴我們應該採取什麼格式 – freefaller

回答

5

你可以使用Linq的一點點,像這樣:

string Hyphenate(string str, int pos) { 
    return String.Join("-", 
     str.Select((c, i) => new { c, i }) 
      .GroupBy(x => x.i/pos) 
      .Select(g => String.Join("", g.Select(x => x.c)))); 
} 

或者這樣:

string Hyphenate(string str, int pos) { 
    return String.Join("-", 
     Enumerable.Range(0, (str.Length - 1)/pos + 1) 
      .Select(i => str.Substring(i * pos, Math.Min(str.Length - i * pos, pos)))); 
} 

或者你可以使用正則表達式,像這樣:

string Hyphenate(string str, int pos) { 
    return String.Join("-", Regex.Split(str, @"(.{" + pos + "})") 
           .Where(s => s.Length > 0)); 
} 

或者是這樣的:

string Hyphenate(string str, int pos) { 
    return String.Join("-", Regex.Split(str, @"(?<=\G.{" + pos + "})(?!$)")); 
} 

所有這些方法都將返回相同的結果:

Console.WriteLine(Hyphenate("abcdxy123z", 2)); // ab-cd-xy-12-3z 
Console.WriteLine(Hyphenate("abcdxy123z", 3)); // abc-dxy-123-z 
Console.WriteLine(Hyphenate("abcdxy123z", 4)); // abcd-xy12-3z 
3

隨着StringBuilder的:

string input = "12345678"; //could be any length 
int position = 3; //could be any other number 
StringBuilder sb = new StringBuilder(); 

for (int i = 0; i < input.Length; i++) 
{ 
    if (i % position == 0){ 
     sb.Append('-'); 
    } 
    sb.Append(input[i]); 
} 
string formattedString = sb.ToString(); 
+1

按位置增加速度要快得多,你不覺得嗎? – Hogan

+0

@Hogan你是對的,它會更快。但我不知道Insert方法。猜我也學到了sometinhg XD – Zzyrk

+0

Substring會讓你不插入就可以做到。 – Hogan

2

for語句的功率:

string str = "12345667889"; 
int loc = 3; 

for(int ins=loc; ins < str.Length; ins+=loc+1) 
    str = str.Insert(ins,"-"); 

給人123-456-678-89

As功能:

string dashIt(string str,int loc) 
{ 
    if (loc < 1) return str; 

    StringBuilder work = new StringBuilder(str); 

    for(int ins=loc; ins < work.Length; ins+=loc+1) 
    work.Insert(ins,"-"); 

    return work.ToString(); 
} 
+0

對於第二個版本爲+1,但是您的第一個代碼部分使用'String.Insert',它返回_new_字符串,每次調用 – Fedor

+0

@Fyodor - true,第一個代碼快速完成以顯示如何使用for語句執行此操作。作爲一個附註,Linq通過p.s.w.g作爲我的第一個代碼示例創建了多個或多個字符串。 – Hogan

+0

當然!我喜歡它也很簡潔,例如,很好的例子,只是指出第二個稍有不同,並且會有點混淆。 – Fedor

相關問題