[英]string.Split() and an if statement
我有一個文本文件,我用\\n
分割。
文本文件(測試)讀取
1
2
3
4
現在令人困惑的部分。
碼
string test = System.IO.File.ReadAllText(@"C:\Custom tests\"+testselect.Text+".txt");
string[] check = test.Split('\n');
if (check[0] == "1")
{
label.Text = "whatever";
}
這不起作用。 標簽保持默認值。 但如果我:
label.Text = check[0];
標簽顯示1。
我不明白這請幫忙。
首先 - 您應該能夠使用File.ReadAllLines
而不是閱讀文本和拆分....
您可能需要修剪結果。 如果行上有額外的空格,則條件可能會失敗。 嘗試使用:
if (check[0].Trim() == "1")
{
這將削減任何空格,這將導致條件成功。
您還可以放入斷點,並檢查調試器中的值。 這有助於您更好地診斷問題。
我相信你應該使用Environment.NewLine。 不同的操作系統使用不同的換行符。
你只是在比較數字嗎? 需要檢查案例和空白..
string.Equals(check[0].Trim(), "some value", StringComparison.OrdinalIgnoreCase);
你可以使用這樣的東西:
如果有的話,刪除退貨
string[] check = test.Replace("\r", "").Split('\n');
if(check[0] == "1")
或者用新行拆分並獲取數組中的字符並檢查它。
string[] check = test.Split('\n');
if(check[0][0] == '1')
我會使用選項二。
編輯:
或類似的東西,但它有點OTT,你得到所有的\\ r \\ n
char[] check = test.SplitMeUp();
if(check[0] == '1')
static class Extensions
{
public static char[] SplitMeUp(this string str)
{
char[] chars = new char[str.Length];
for (int i = 0; i < chars.Length; i++)
chars[i] = str[i];
return chars;
}
}
編輯:
過濾掉特定字符的其他內容
public static char[] SplitMeUp(this string str, char[] filterChars = null)
{
List<Char> chars = new List<char>();
for (int i = 0; i < str.Length; i++)
{
if(filterChars != null && filterChars.Length > 0 && filterChars.Contains(str[i]))
continue;
chars.Add(str[i]);
}
return chars.ToArray();
}
並使用它
char[] check = test.SplitMeUp(new char[] {'\r', '\n'});
if(check[0] == '1')
它將忽略所有這些\\ r \\ n並將所有內容分開。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.