我想在第一次出現給定字符後修剪字符串的末尾,在這種情況下爲'。'。如何在第一次出現字符後修整字符串的末尾C#
此字符在字符串中出現多次。
- 輸入:143.122.124.123
- 輸出:143
我能找到類似這樣的多個問題alhtough它們都使用LastIndexOf()
;因爲這需要第一次出現並移除字符串的其餘部分。
我想在第一次出現給定字符後修剪字符串的末尾,在這種情況下爲'。'。如何在第一次出現字符後修整字符串的末尾C#
此字符在字符串中出現多次。
我能找到類似這樣的多個問題alhtough它們都使用LastIndexOf()
;因爲這需要第一次出現並移除字符串的其餘部分。
input.Substring(0, input.IndexOf('.'))
說明:
String.IndexOf(char)
拿到第一個字符出現的從零開始的索引中的字符串。例如。對於您的輸入,它將是索引爲3
的第四個字符。String.Substring(startIndex,length)
從字符串的開始處獲取子字符串。使用char的索引作爲子串的長度,因爲索引是從零開始的。注:該解決方案的
優點(相比於使用Split
)是它不會製造存儲器陣列中,並不會遍歷所有字符串搜索分裂的性格和提取子。
這個解決方案的缺點是字符串必須包含至少一個你正在尋找的字符(感謝Ivan Chepikov提到它)。安全的替代品將看起來像
int index = input.IndexOf('.');
if (index != -1)
substring = input.Substring(0, index);
其實,有很多的選擇,做你想要什麼:
input.Substring(0, input.IndexOf('.'))
input.Split('.')[0]
Regex.Match(input, @"[^\.]*").Value
new string(input.TakeWhile(ch => ch != '.').ToArray())
input.SubstringUpTo('.')
這將是很好的檢查input.IndexOf('。')!= -1只是爲了確保輸入包含字符。 –
string input = "143.122.124.123";
string output = input.Split('.')[0];
這將返回整個字符串,如果沒有找到Split
字符。
'input.Split(new char [] {'。'},2)'是一個更好的選擇(對於有很多點的長字符串的情況) –
@DmitryBychenko其實我認爲你可以將計數傳遞爲'1'比'2'。 –
@Matthew Watson:對不起,我們想要'2'項目,他們是:'143'和'122.124.123' –
(我發佈這只是爲了完整性 - 謝爾蓋的答案似乎是正確和最簡單的。)
(1)一個LINQ方法:
s = new string(s.TakeWhile(c => c != '.').ToArray());
(2)同謝爾蓋的回答,但使用Left()
字符串擴展:
string s = "143.122.124.123";
s = s.Left(s.IndexOf('.'));
真正應該做的錯誤,雖然檢查:
string s = "143.122.124.123";
int n = s.IndexOf('.');
if (n >= 0)
s = s.Left(n);
注:Left()
方法實際上是一個擴展方法,所以實際上它只是同謝爾蓋的回答是:
public static class StringExt
{
public static string Left(this string self, int count)
{
string result = self.Length <= count
? self
: self.Substring(0, count);
return result;
}
}
你可以給一個'Left'方法文檔的鏈接嗎? –
@SergeyBerezovskiy Ooops我不小心使用了擴展方法;我會添加它! –
謝謝,現在很清楚。我以爲有一些框架更新,我錯過了:) –
而現在我們得到了堅果和堅持使用.LastIndexOf()
:
string input = "143.122.124.123";
string rev = new string(input.Reverse().ToArray());
string output = new string(rev.Substring(rev.LastIndexOf('.') + 1).Reverse().ToArray());
使用的IndexOf而不是LastIndexOf呢? :) – john
許多類似的主題:1. http://stackoverflow.com/questions/6578254/to-get-specific-part-of-a-string-in-c-sharp 2. http://stackoverflow.com/ question/10868517/split-string-and-get-first-value-only – swdev95
[在字符串末尾的trim字符串]的可能重複(http://stackoverflow.com/questions/4226657/trim-string-at-字符串末尾) – Fabiano