拆分不同字符之间的整数

时间:2016-05-30 09:40:54

标签: c# unity3d

我想从文件中读取整数,例如我想从这样的文件中读取一个向量(0,0,0)并且我想保存每个参数,x = 0 y = 0 z = 0怎么能我拆分字符串并保存整数。我有一个读取整数的读取程序,但问题来自于我有一个双位整数,程序没有读取正确的值。我的文本文件是这样的:

  angular.module('myModule',['ngCookies']) //injecting cookies module in app
    .factory('myWarehouse', myWarehouseFactory);

  myWarehouseFactory.$inject = ['Workers', 'Food','$cookies']; //injecting in factory

  function myWarehouseFactory( Workers, Food, $cookies ) {

    return function() {
      Workers.atWork(true)
        .then(function() {

          var familiar = $cookies.get('Workers');

          $cookies.put(familiar, 'John');

          if ('John' == familiar) {
            // Do something
          }

        });
    };
  }

1 个答案:

答案 0 :(得分:3)

您可以尝试使用常规表达式,如下所示:

  // Possible operations
  Dictionaty<String, Func<int, int, int, MyObject>> operations =
    new Dictionaty<String, Func<int, int, int, MyObject>>() {
      {"Cube.Attach", (x, y, z) => Cube.Attach(x, y, z);},
      {"Tree.Attach", (x, y, z) => Tree.Attach(x, y, z);},
      {"Plain.Attach", (x, y, z) => Plain.Attach(x, y, z);},
      {"Terrain.Attach", (x, y, z) => Terrain.Attach(x, y, z);},
      ... 
    }
  ...

  // Please, notice spaces and minus sign (-125)
  String source = ":Cube.Attach(100, 18, -125);";

  ...

  String pattern = @"^:(?<Func>[A-Za-z.]+)\((?<Args>.+)\);$";

  Match match = Regex.Match(source, pattern);

  if (match.Success) {
    // Operation name - "Cube.Attach" 
    // Comment it out if you don't want it 
    String func = match.Groups["Func"].Value;

    // Operation arguments - [100, 18, -125]
    int[] args = match.Groups["Args"].Value
      .Split(',')
      .Select(item => int.Parse(item, CultureInfo.InvariantCulture))
      .ToArray();

    // Let's find out proper operation in the dictionary and perform it
    // ... or comment it out if you don't want perform the operation here
    operations[func](args[0], args[1], args[2]); 
  }

如果您想要分割"(0,0,0)",则不需要正则表达式,因为SplitTrim就足够了:

  String source = "(100, 18, -125)";

  // [100, 18, -125] 
  int[] args = source
    .Trim('(', ')')
    .Split(',')
    .Select(item => int.Parse(item, CultureInfo.InvariantCulture)) 
    .ToArray();

  // finally, if you need it
  int x = args[0];
  int y = args[1];
  int z = args[2];