开发者

Slice a string in two or more parts in c#

I have a string like this (c#, winforms):

private string source = @"CDM_DEBUG\D1_XS1000psc_1"

I want to have this string in two parts, first part should be everything before the last underscore that will be 'CDM_DEBUG\D1_XS1000psc' and second part should be '_1'.

Then I want to make a new string from the first part and make it to 'CDM_DEBUG\D1_XS1000psc_2'

what is the faste开发者_Go百科st way of doing this?


Check out String.LastIndexOf.

int lastUnderscore = source.LastIndexOf('_');
if (lastUnderscore == -1)
{
    // error, no underscore
}

string firstPart = source.Substring(0, lastUnderscore);
string secondPart = source.Substring(lastUnderscore);

Is it faster than regular expressions? Possibly. Possibly not.


Maybe something like this would work?

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;
}


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;
}


Indices and ranges functionality is available in C# 8.0+ allowing you to split the string with the following succinct syntax:

var firstPart = source[..^2]; 

var secondPart = source[^2..];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜