[英]Can I shorten this code with a loop in C#?
我用 C# 編寫了這段代碼,但看起來有點“糟糕”,我想以某種方式縮短它並保持簡潔。 所有這些代碼都很好,但我想知道是否有其他方法可以實現相同的目標。
編輯:我忘了提到 firstLine 附帶了錯誤的日期格式,所以它是這樣的: "This_is_my_first_line_20220126"
。 所以我拆分了字符串,然后只用更正的日期加入它。 問題是我永遠不知道新字符串有多長,我不想處理這樣的代碼和 go 多達 100 個部分。
這是我的代碼:
string correctDate = "26012022";
string[] lines = File.ReadAllLines("text.txt");
string firstLine = lines.FirstOrDefault();
//note: firstLine looks like this: This_is_my_first_line_20220126
string[] sub = firstLine.Split('_');
string name="";
if(sub.Length==2)
name = sub[0]+"_"+sub[1]+"_"+correctDate;
else if(sub.Length==3)
name = sub[0]+"_"+sub[1]+"_"+sub[2]+"_"correctDate;
...
else if(sub.Length==20)
name = sub[0]+"_"+ ... "_" + sub[19];
現在,我的最終名稱值應該是"This_is_my_line_26012022"
,但我希望它取決於給定字符串的長度。 到目前為止,我知道最大長度 go 最多為 20,但我不希望我的代碼看起來像這樣。 我可以以某種方式縮短它嗎?
您可以使用Substring找到下划線的LastIndexOf並刪除日期:
string firstLine = "This_is_my_first_line_20220126";
string correctDate = "26012022";
string correctString = firstLine.Substring(0, firstLine.LastIndexOf("_") + 1) + correctDate;
仍然對拆分方法感到困惑,但這是一種連接所有元素的方法
string name = string.Join("_", sub.Take(sub.Length - 1).Append(correctDate));
或者使用 substring 方法(並且不需要所有的拆分和連接)
name = firstLine.Substring(0, firstLine.LastIndexOf("_") +1) + correctDate;
我忘了提到 firstLine 的日期格式不好,例如“This_is_my_Line_20220125”
如果您只想更正第一行:
string correctDate = "26012022";
string[] lines = File.ReadAllLines("text.txt");
lines[0] = lines[0][..^8] + correctDate;
[..^8]
使用 C# 9 的“索引和范圍”功能,允許采用更緊湊的方式獲取 substring。 它的意思是“從字符串的開頭,到字符串末尾的索引 8”。
如果您收到一條擺動的線,並且可能出現類似“...在 C# 版本 X 中不可用”之類的消息,您可以使用較舊的語法,這更像是lines[0] = lines[0].Remove(lines[0].Length - 8) + correctDate;
如果要更正所有行:
string correctDate = "26012022";
string[] lines = File.ReadAllLines("text.txt");
for(int x = 0; x < lines.Length; x++)
lines[x] = lines[x][..^8] + correctDate;
如果不正確的日期並不總是 8 個字符長,您可以使用 LastIndexOf('_') 找到最后一個_
,並將其剪切到該點
.
string[] lines = File.ReadAllLines("text.txt");
string firstLine = lines.FirstOrDefault();
name = firstLine.Substring(0, firstLine.LastIndexOf("_") + 1) + + "_" + correctDate ; ```
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.