![](/img/trans.png)
[英]How would I detect the last two occurrence of characters/data sets in a text file c#
[英]Extract All Characters after last occurrence of a pattern C#
字符串具有以下模式
1.0.0.0
1.0.0.1
1.0.0.2
...
...
...
我正在尋找一個代碼,它將讀取最后創建的字符串並將最后一個數字遞增1並將其另存為新字符串。
我該怎么做?
最好的祝福,
魔法
您可以將字符串拆分為組件,解析最后一個組件以便可以增加它們,然后將它們重新組合在一起:
string[] parts = version.Split('.');
parts[3] = (Int32.Parse(parts[3]) + 1).ToString();
version = String.Join(".", parts);
另一種可能稍微高效的方法是使用字符串操作僅獲取最后一個組件:
int pos = version.LastIndexOf('.') + 1;
int num = Int32.Parse(version.Substring(pos));
version = version.Substring(0, pos) + num.ToString();
如果您的目的是始終獲取特定字符后的最后一個子字符串(當然不包括分隔符字符(在本例中為句點)),我相信您的意圖:
使用1個襯墊保持簡單:
string myLastSubString = myStringToParse.Split('.').Last();
我會讓其他帖子回答您的其余查詢。
public string DoMagic(string s)
{
string t = s.Substring(s.LastIndexOf(' ')+1);
return t.Substring(0, t.Length-1) + (int.Parse(t[t.Length-1].ToString())+1).ToString();
}
假設格式不會改變,這可能是您的最佳解決方案。 這將適用於無序版本列表字符串。
string VersionList = "1.0.0.0 1.0.0.1 1.0.0.2";
List<Version> Versions = new List<Version>();
foreach (string FlatVersion in VersionList.Split(' '))
Versions.Add(new Version(FlatVersion));
Versions.Sort(); Versions.Reverse();
Version MaximumVersion = Versions[0];
Version NewVersion = new Version(
MaximumVersion.Major,
MaximumVersion.MajorRevision,
MaximumVersion.Minor,
MaximumVersion.MinorRevision + 1);
假設您的字符串列表是:
List<string> stringList;
您可以使用以下命令獲取該列表中的最后一項:
string lastString = stringList[stringList.Length - 1];
然后使用以下方法獲取該字符串的最后一個字
char c = lastString[lastString.Length - 1];
將char轉換並遞增為十進制:
int newNum = Int32.Parse(c.ToString()) + 1;
最后,復制原始字符串並用新的字符替換最后一個數字:
string finalString = lastString;
finalString[finalString.Length - 1] = c;
現在將其添加回原始列表:
stringList.Add(finalString);
假設只有子字符串中的最后一個元素變化:
List<string> items = GetItems();
string[] max = input.Split(' ').Max().Split('.');
string next = string.Format("{0}.{1}.{2}.{3}", max[0], max[1], max[2], int.Parse(max[3]) + 1);
我現在正在使用VB,但是對C#的翻譯應該是直截了當的。 從這里實現你的實際問題應該是直截了當的 - 你有一個集合,最后一項是最后一個數字,只需增加它並替換集合的最后一項並再次寫出來。
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim matchC As MatchCollection = Regex.Matches("111.222.333", "\d+")
Dim i As Integer = 1
For Each x In matchC
Console.Write(i.ToString & " ")
Console.WriteLine(x)
i = i + 1
Next
' remember to check the case where no matches occur in your real code.
Console.WriteLine("last number is " & matchC.Item(matchC.Count - 1).ToString)
Console.ReadLine()
End Sub
End Module
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.