C# 在c语言中将字符串分成两部分或更多部分#
我有这样一个字符串(c#,winforms): 我想把这个字符串分为两部分,第一部分应该是最后一个下划线之前的所有内容,即“CDM_DEBUG\D1_XS1000psc”,第二部分应该是“_1” 然后我想从第一部分创建一个新字符串,并将其设置为“CDM_DEBUG\D1_XS1000psc_2”C# 在c语言中将字符串分成两部分或更多部分#,c#,string,slice,C#,String,Slice,我有这样一个字符串(c#,winforms): 我想把这个字符串分为两部分,第一部分应该是最后一个下划线之前的所有内容,即“CDM_DEBUG\D1_XS1000psc”,第二部分应该是“_1” 然后我想从第一部分创建一个新字符串,并将其设置为“CDM_DEBUG\D1_XS1000psc_2” 最快的方法是什么?查看String.LastIndexOf int lastUnderscore = source.LastIndexOf('_'); if (lastUnderscore == -1)
最快的方法是什么?查看
String.LastIndexOf
int lastUnderscore = source.LastIndexOf('_');
if (lastUnderscore == -1)
{
// error, no underscore
}
string firstPart = source.Substring(0, lastUnderscore);
string secondPart = source.Substring(lastUnderscore);
它比正则表达式快吗?可能地可能不行。也许像这样的办法行得通
private const char fileNumberSeparator = '_';
private static string IncrementFileName(string fileName)
{
if (fileName == null)
throw new ArgumentNullException("fileName");
fileName = fileName.Trim();
if (fileName.Length == 0)
throw new ArgumentException("No file name was supplied.", "fileName");
int separatorPosition = fileName.LastIndexOf(fileNumberSeparator);
if (separatorPosition == -1)
return AppendFileNumber(fileName, 1);
string prefix = fileName.Substring(0, separatorPosition);
int lastValue;
if (int.TryParse(fileName.Substring(separatorPosition + 1, out lastValue)
return AppendFileNumber(prefix, lastValue + 1);
else
return AppendFileNumber(fileName, 1);
}
private static string AppendFileNumber(string fileNamePrefix, int fileNumber)
{
return fileNamePrefix + fileNumberSeparator + fileNumber;
}
C#8.0+中提供的功能允许您使用以下简洁语法拆分字符串:
var firstPart = source[..^2];
var secondPart = source[^2..];
@Jeffry感谢您提供了漂亮的代码,但我的字符串并没有实现为文件,但您的代码对以后很有用!
string doc = @"CDM_DEBUG\D1_XS1000psc_1";
var lastPos = doc.LastIndexOf("_");
if(lastPos!=-1){
string firstPart = doc.Substring(0,lastPos);
string secondPart = doc.Substring(lastPos);
var nextnumber = Int32.Parse(secondPart.TrimStart('_'))+1;
var output = firstPart + "_" + nextnumber;
}
var firstPart = source[..^2];
var secondPart = source[^2..];