Skip to main content
 首页 » 编程设计

c#之字符串替换参数

2024年02月13日21lhb25

(C#)我的代码似乎没问题,但每当我将 0 作为第二个参数时,它就会显示 “Enemy50”,当我希望敌人 57 变为敌人 00 时。我认为第三个 if 语句有问题但不确定是否修复它。

主要

   string enemy57 = "enemy57"; 
   Console.WriteLine("The old image name is: " + enemy57); 
   Console.WriteLine("New image name: " + BuildingBlock.NextImageName(enemy57, 0)); 
   Console.ReadLine(); 
 
 
class BuildingBlock 
{ 
    public static string ReplaceOnce(string word, string characters, int position) 
    { 
        word = word.Remove(position, characters.Length); 
        word = word.Insert(position, characters); 
        return word; 
    } 
 
    public static string GetLastName(string name) 
    { 
        string result = ""; 
        int posn = name.LastIndexOf(' '); 
        if (posn >= 0) result = name.Substring(posn + 1); 
        return result; 
    } 
 
    public static string NextImageName(string filename, int newNumber) 
    { 
 
        if (newNumber > 9) 
        { 
            return ReplaceOnce(filename, newNumber.ToString(), (filename.Length - 2)); 
        } 
        if (newNumber < 10) 
        { 
            return ReplaceOnce(filename, newNumber.ToString(), (filename.Length - 1)); 
        } 
        if (newNumber == 0) 
        { 
            return ReplaceOnce(filename, newNumber.ToString(), (filename.Length - 2)); 
        } 
        return filename; 
    } 

请您参考如下方法:

这是一个可能会满足您要求的示例。

它将:

  1. 用新数字替换所有最后的数字
  2. 确保字符串中新数字的位数与字符串中原始数字的位数相同(或更多,如果需要)

意思是:

Enemy01, replace with 5, will be Enemy05 
Enemy57, replace with 5, will be Enemy05 
Enemy1, replace with 57, will be Enemy57 

这是一个 LINQPad演示的程序:

void Main() 
{ 
    NextImageName("Enemy01", 5).Dump(); 
    NextImageName("Enemy57", 5).Dump(); 
    NextImageName("Enemy5", 57).Dump(); 
} 
 
public static string NextImageName(string filename, int newNumber) 
{ 
    var re = new Regex(@"\d+$"); 
    return re.Replace(filename, match => 
    { 
        return newNumber.ToString().PadLeft(match.Length, '0'); 
    }); 
} 

输出:

Enemy05 
Enemy05 
Enemy57 

正则表达式

\d+$ 

意思是:

  +- one or more times 
  v 
\d+$ 
^^ ^ 
 | | 
 | +-- followed by the end of the string 
 | 
 digits (0-9) 

换句话说:

  • 一个或多个数字 (0-9)
  • 跟在字符串的末尾