Int/将数字列表转换成字符串

本文关键字:转换 字符串 列表 数字 Int | 更新日期: 2023-09-27 17:51:08

我有一个如下所示的数字字符串。下面是一个随机数。如果我想检查随机数是否等于字符串中的某个数我该怎么做呢?

          public string[] List = { "5", "3","9" };
            int test = random.Next(1, 10);

现在我有以下内容。所有这些都适用于我的脚本,除了if (test == number),测试是定义的随机和数字是我试图弄清楚如何将其引用到配置。List,它是5 3 9的列表。因为不能在同一个if语句中同时使用string和int。

         foreach (string number in config.List)
            {
                if (test == number)
                {
                    TSPlayer.All.SendSuccessMessage("counting count = {0} number = {1}", count, test);
                }
                if (test >= 5)
                {
                    int amount = 200;
                    int monsteramount = 303;
                    NPC npcs = TShock.Utils.GetNPCById(monsteramount);
                    TSPlayer.All.SendSuccessMessage("#5 exists! count = {0} number = {1}", count, test);
                    TSPlayer.Server.SpawnNPC(npcs.type, npcs.name, amount, args.Player.TileX, args.Player.TileY, 50, 20);
                    TSPlayer.All.SendSuccessMessage(string.Format("{0} has spawned {1} {2} time(s).", args.Player.Name, npcs.name, amount));
                    break;
                }
            }
        }
    }

Int/将数字列表转换成字符串

如果我正确理解您的问题,您需要将整数的string表示转换为int

可以像这样将字符串转换为整型:

string str = "5";
int val = Convert.ToInt32(str);   // val will be 5.

如果你不能相信你的输入(即,你不能100%确定字符串是一个有效的数字),那么你可以这样使用Int32.TryParse:

string str = "5";
int val;
if ( Int32.TryParse(str, out val) ) {
    // conversion was successful, val == 5
} else { 
    // conversion failed. 
}

或者,您可以将int转换为string,这是最容易做到的,如下所示:

int val = 5;
string str = val.ToString();

要更具体,您需要使用第一种方法,如下所示:

foreach (string number in config.List)
{
    var val = Convert.ToInt32(number);
    if (test == val)
    {
        // ...
    }
    ...
}

或者需要使用第二种方法,像这样:

foreach (string number in config.List)
{
    if (test.ToString() == number)
    {
        // ...
    }
    ...
}

无论如何,你必须确保你的类型匹配。

更新2

这是字面上的代码你的问题,现在(结合顶部和底部的部分),只有一个改变,应该使这一个单一的编译错误消失:

public string[] List = { "5", "3","9" };
int test = random.Next(1, 10);
foreach (string number in config.List)
{
    if (test.ToString() == number)  // This is the line I changed
    {
        // do your thing
    }
    if (test >= 5)
    {
        int amount = 200;
        int monsteramount = 303;
        NPC npcs = TShock.Utils.GetNPCById(monsteramount);
        TSPlayer.All.SendSuccessMessage("#5 exists! count = {0} number = {1}", count, test);
        TSPlayer.Server.SpawnNPC(npcs.type, npcs.name, amount, args.Player.TileX, args.Player.TileY, 50, 20);
        TSPlayer.All.SendSuccessMessage(string.Format("{0} has spawned {1} {2} time(s).", args.Player.Name, npcs.name, amount));
        break;
    }
}
var listOfInts = List.Select(s => int.Parse(s));
if(listOfInts.Contains(test))
{
  // Do stuff
}