最后一次出现模式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();
我会让其他post回答您的其余查询。
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 Versions = new List (); 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 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 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