![](/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.