删除除最后一个字符之外的特定字符

发布于 2025-01-09 14:19:29 字数 844 浏览 0 评论 0原文

我有一个文本字符串,我想用下划线替换点,除了字符串中找到的最后一个字符。

示例:

input = "video.coffee.example.mp4"
result = "video_coffe_example.mp4"

我有一个代码,但这替换了所有内容,包括最后一个字符

第一个选项失败了

static string replaceForUnderScore(string file)
{
     return file = file.Replace(".", "_");
}

我实现了第二个适合我的选项,但我发现它非常广泛并且不是很优化

static string replaceForUnderScore(string file)
{
     string result = "";

     var splits = file.Split(".");
     var extension = splits.LastOrDefault();

     splits = splits.Take(splits.Count() - 1).ToArray();

     foreach (var strItem in splits)
     {
         result = result + "_" + strItem;
     }

     result = result.Substring(1, result.Length-1);
     string finalResult = result + "."+extension;

     return finalResult;
 }

有没有更好的方法来做到这一点?

I have a text string and I want to replace the dots with underscores except for the last character found in the string.

Example:

input = "video.coffee.example.mp4"
result = "video_coffe_example.mp4"

I have a code but this replaces everything including the last character

first option failed

static string replaceForUnderScore(string file)
{
     return file = file.Replace(".", "_");
}

I implemented a second option that works for me but I find that it is very extensive and not very optimized

static string replaceForUnderScore(string file)
{
     string result = "";

     var splits = file.Split(".");
     var extension = splits.LastOrDefault();

     splits = splits.Take(splits.Count() - 1).ToArray();

     foreach (var strItem in splits)
     {
         result = result + "_" + strItem;
     }

     result = result.Substring(1, result.Length-1);
     string finalResult = result + "."+extension;

     return finalResult;
 }

Is there a better way to do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

失而复得 2025-01-16 14:19:34

最简单(也可能是最快)的方法就是迭代字符串:

static string replaceForUnderScore(string file)
{
  StringBuilder sb      = new StringBuilder( file.Length ) ;
  int           lastDot = -1 ;

  for ( int i = 0 ; i < file.Length ; ++i )
  {
    char c = file[i] ;

    // if we found a '.', replace it with '_' and save its position
    if ( c == '.' )
    {
      c       = '_' ;
      lastDot = i   ;
    }


    sb.Append( c ) ;

  }

  // if we changed any '.' to '_', convert the last such replacement back to '.'
  if ( lastDot >= 0 )
  {
    sb.Replace ( '.' , '_' , lastDot, 1 );
  }

  return sb.ToString();
}

另一种方法是使用 System.IO.Path。这当然是最简洁的:

static string replaceForUnderScore( string file )
{
  string ext  = Path.GetExtension( file ) ;
  string name = Path
                .GetFileNameWithoutExtension( file )
                .Replace( '.' , '_' )
                ;

  return Path.ChangeExtension( name , ext ) ;
}

The simplest (and probably fastest) way is just to iterate over the string:

static string replaceForUnderScore(string file)
{
  StringBuilder sb      = new StringBuilder( file.Length ) ;
  int           lastDot = -1 ;

  for ( int i = 0 ; i < file.Length ; ++i )
  {
    char c = file[i] ;

    // if we found a '.', replace it with '_' and save its position
    if ( c == '.' )
    {
      c       = '_' ;
      lastDot = i   ;
    }


    sb.Append( c ) ;

  }

  // if we changed any '.' to '_', convert the last such replacement back to '.'
  if ( lastDot >= 0 )
  {
    sb.Replace ( '.' , '_' , lastDot, 1 );
  }

  return sb.ToString();
}

Another approach would be to use System.IO.Path. It's certainly the most succinct:

static string replaceForUnderScore( string file )
{
  string ext  = Path.GetExtension( file ) ;
  string name = Path
                .GetFileNameWithoutExtension( file )
                .Replace( '.' , '_' )
                ;

  return Path.ChangeExtension( name , ext ) ;
}
稍尽春風 2025-01-16 14:19:32

在我的脑海中,但这可能会起作用。

return $"{file.Replace(".mp4","").Replace(".","_")}.mp4";

Off the top of my head but this might work.

return 
quot;{file.Replace(".mp4","").Replace(".","_")}.mp4";
一笑百媚生 2025-01-16 14:19:31

由于您使用文件,我建议使用 路径类:全部
我们想要的是仅更改文件名,同时保持扩展名不变:

static string replaceForUnderScore(string file) =>
  Path.GetFileNameWithoutExtension(file).Replace('.', '_') + Path.GetExtension(file);

Since you work with files, I suggest using Path class: all
we want is to change file name only while keeping extension intact:

static string replaceForUnderScore(string file) =>
  Path.GetFileNameWithoutExtension(file).Replace('.', '_') + Path.GetExtension(file);
浮萍、无处依 2025-01-16 14:19:31

正则表达式将帮助您做到这一点。

添加命名空间 using System.Text.RegularExpressions;

并使用以下代码:

var regex = new Regex(Regex.Escape("."));
var newText = regex.Replace("video.coffee.example.mp4", "_", 2);

这里我们指定了替换 的最大次数。

输出如下:

video_coffee_example.mp4

此外,您可以更新代码以替换除最后一个点之外的任意数量点。

    var replaceChar = '.';
    var regex = new Regex(Regex.Escape(replaceChar.ToString()));
    var replaceWith = "_";
    // The text to process
    var text = "video.coffee.example.mp4";
    // Count how many chars to replace excluding extension
    var replaceCount = text.Count(s => s == replaceChar) - 1;
    var newText = regex.Replace(text, replaceWith, replaceCount);

Regex will help you to do this.

Add the namespace using System.Text.RegularExpressions;

And use this code:

var regex = new Regex(Regex.Escape("."));
var newText = regex.Replace("video.coffee.example.mp4", "_", 2);

Here we specified the maximum number of times to replace the .

The output would be the following:

video_coffee_example.mp4

Additionally, you can update the code to replace any number of dots excluding the last one.

    var replaceChar = '.';
    var regex = new Regex(Regex.Escape(replaceChar.ToString()));
    var replaceWith = "_";
    // The text to process
    var text = "video.coffee.example.mp4";
    // Count how many chars to replace excluding extension
    var replaceCount = text.Count(s => s == replaceChar) - 1;
    var newText = regex.Replace(text, replaceWith, replaceCount);
野鹿林 2025-01-16 14:19:31

您可以通过断言匹配时右侧仍然存在一个点,将除最后一个点之外的所有点替换为下划线。

string result = Regex.Replace(input, @"\.(?=[^.]*\.)", "_");

结果将是

video_coffee_example.mp4

You can replace all the dots with an underscore except for the last dot by asserting that there is still a dot present to the right when matching one.

string result = Regex.Replace(input, @"\.(?=[^.]*\.)", "_");

The result will be

video_coffee_example.mp4
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文