简体   繁体   English

在 c# 中将字符串分成两部分或更多部分

[英]Slice a string in two or more parts in c#

I have a string like this (c#, winforms):我有一个这样的字符串(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'.我想将此字符串分为两部分,第一部分应该是最后一个下划线之前的所有内容,即“CDM_DEBUG\D1_XS1000psc”,第二部分应该是“_1”。

Then I want to make a new string from the first part and make it to 'CDM_DEBUG\D1_XS1000psc_2'然后我想从第一部分创建一个新字符串并将其设置为 'CDM_DEBUG\D1_XS1000psc_2'

what is the fastest way of doing this?最快的方法是什么?

Check out String.LastIndexOf .查看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: C# 8.0+ 中提供了索引和范围功能,允许您使用以下简洁语法拆分字符串:

var firstPart = source[..^2]; 

var secondPart = source[^2..];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM