【发布时间】:2014-01-05 16:53:05
【问题描述】:
(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;
}
【问题讨论】:
-
这不是你一个小时前问的几乎一样的问题吗? stackoverflow.com/questions/20927305/…
-
@SonerGönül 不,我解决了这个问题,但现在它只是一个小问题
-
如果 newNumber 为零,您将调用 ReplaceOnce 两次。一次是因为数字小于 10,一次是因为它是零。这是你想要的吗?
-
如果将 Enemy5 替换为 57 会发生什么?敌人57?如果您的代码不查看现有数字但假定当前字符串已经包含正确的数字位数,那么您的代码本身就有缺陷。