我去創造空間「ThisCourse」的方式來「這門課程」資本字母之間創造空間和跳躍空間之間的連續
Add Space Before Capital Letter By (EtienneT) LINQ Statement
,但我不能
創造空間Betweeen這種「 ThisCourseID「爲」此課程ID「之間沒有」ID「之間的空間
有沒有辦法在Linq做到這一點?
我去創造空間「ThisCourse」的方式來「這門課程」資本字母之間創造空間和跳躍空間之間的連續
Add Space Before Capital Letter By (EtienneT) LINQ Statement
,但我不能
創造空間Betweeen這種「 ThisCourseID「爲」此課程ID「之間沒有」ID「之間的空間
有沒有辦法在Linq做到這一點?
好吧,如果它是一個單一的LINQ語句...
var s = "ThisCourseIDMoreXYeahY";
s = string.Join(
string.Empty,
s.Select((x,i) => (
char.IsUpper(x) && i>0 &&
(char.IsLower(s[i-1]) || (i<s.Count()-1 && char.IsLower(s[i+1])))
) ? " " + x : x.ToString()));
Console.WriteLine(s);
輸出:「This Course ID More X Yeah Y」
非常Goooood謝謝... – 2012-04-03 10:16:12
寫得很好=) – Marchy 2014-03-02 21:47:58
var s = "ThisCourseID";
for (var i = 1; i < s.Length; i++)
{
if (char.IsLower(s[i - 1]) && char.IsUpper(s[i]))
{
s = s.Insert(i, " ");
}
}
Console.WriteLine(s); // "This Course ID"
您可以改善這種使用StringBuilder的,如果你要使用這個在很長的字符串,但你的目的,你提出的,它應該只是罰款。
FIX:
var s = "ThisCourseIDSomething";
for (var i = 1; i < s.Length - 1; i++)
{
if (char.IsLower(s[i - 1]) && char.IsUpper(s[i]) ||
s[i - 1] != ' ' && char.IsUpper(s[i]) && char.IsLower(s[i + 1]))
{
s = s.Insert(i, " ");
}
}
Console.WriteLine(s); // This Course ID Something
你不需要LINQ - 但你可以「枚舉」和使用拉姆達,使其更通用...
(雖然不知道是否有任何這使得感覺)
static IEnumerable<string> Split(this string text, Func<char?, char?, char, int?> shouldSplit)
{
StringBuilder output = new StringBuilder();
char? before = null;
char? before2nd = null;
foreach (var c in text)
{
var where = shouldSplit(before2nd, before, c);
if (where != null)
{
var str = output.ToString();
switch(where)
{
case -1:
output.Remove(0, str.Length -1);
yield return str.Substring(0, str.Length - 1);
break;
case 0: default:
output.Clear();
yield return str;
break;
}
}
output.Append(c);
before2nd = before;
before = c;
}
yield return output.ToString();
}
...並稱之爲像這樣...
static IEnumerable<string> SplitLines(this string text)
{
return text.Split((before2nd, before, now) =>
{
if ((before2nd ?? 'A') == '\r' && (before ?? 'A') == '\n') return 0; // split on 'now'
return null; // don't split
});
}
static IEnumerable<string> SplitOnCase(this string text)
{
return text.Split((before2nd, before, now) =>
{
if (char.IsLower(before ?? 'A') && char.IsUpper(now)) return 0; // split on 'now'
if (char.IsUpper(before2nd ?? 'a') && char.IsUpper(before ?? 'a') && char.IsLower(now)) return -1; // split one char before
return null; // don't split
});
}
...某處...
var text = "ToSplitOrNotToSplitTHEQuestionIsNow";
var words = text.SplitOnCase();
foreach (var word in words)
Console.WriteLine(word);
text = "To\r\nSplit\r\nOr\r\nNot\r\nTo\r\nSplit\r\nTHE\r\nQuestion\r\nIs\r\nNow";
words = text.SplitLines();
foreach (var word in words)
Console.WriteLine(word);
:)
回答哪個答案你試試? – BoltClock 2012-04-01 12:43:50
另請參閱http://stackoverflow.com/a/9861239/932418 – 2012-04-01 12:50:24
爲什麼你需要LINQ? – BoltClock 2012-04-01 13:22:20