2016-08-02 22 views
2

ここでは3つの整数を持つ文字列を3つの整数変数に格納したいが、答えを見つけることができない。文字列を整数配列に変換する

string orders = "Total orders are 2222 open orders are 1233 closed are 222"; 

これは私がしたいことです。

int total = 2222; 
int close = 222; 
int open = 1233; 
+1

は固定文字列ですが、それは "総受注は###オープン注文は###されている...." いつものだろうか? –

答えて

5

(パターンを抽出するために)とLINQのint[]にそれらを整理する)正規表現を使用してみてください:あなたは順番に各文字を検査し、それがあるかどうかを確認することができます

string orders = "Total orders are 2222 open orders are 1233 closed are 222"; 

    int[] result = Regex 
    .Matches(orders, "[0-9]+") 
    .OfType<Match>() 
    .Select(match => int.Parse(match.Value)) 
    .ToArray(); 
0

数値:

string orders = "Total orders are 2222 open orders are 1233 closed are 222"; 

List<int> nums = new List<int>(); 
StringBuilder sb = new StringBuilder(); 

foreach (Char c in orders) 
{ 
    if (Char.IsDigit(c)) 
    { 
     //append to the stringbuilder if we find a numeric char 
     sb.Append(c); 
    } 
    else 
    { 
     if (sb.Length > 0) 
     { 
      nums.Add(Convert.ToInt32(sb.ToString())); 
      sb = new StringBuilder(); 
     } 
    } 
} 

if (sb.Length > 0) 
{ 
    nums.Add(Convert.ToInt32(sb.ToString())); 
} 

//nums now contains a list of the integers in the string 
foreach (int num in nums) 
{ 
    Debug.WriteLine(num); 
} 

出力:

ここで
2222 
1233 
222 
1

あなたが唯一のLINQを使用してそれを行うことができます一つの方法

namespace StringToIntConsoleApp 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string orders = "Total orders are 2222 open orders are 1233 closed are 222"; 
      string[] arr = orders.Split(' '); 
      List<int> integerList = new List<int>(); 
      foreach(string aString in arr.AsEnumerable()) 
      { 
       int correctedValue ; 
       if(int.TryParse(aString,out correctedValue)) 
       { 
        integerList.Add(correctedValue); 
       } 
      } 

      foreach (int aValue in integerList) 
      { 
       Console.WriteLine(aValue); 
      } 
      Console.Read(); 
     } 
    } 
} 
4

です:

int[] result = orders 
    .Split(' ') 
    .Where(s => s 
    .ToCharArray() 
    .All(c => Char.IsDigit(c))) 
    .Select(s => Int32.Parse(s)) 
    .ToArray(); 
+0

質問に*整数配列* –

+0

Thxが必要なので、 'Select'と' ToArray'を追加することをお勧めします。私は答えを編集しました –

+0

'Char.IsDigit'に注意してください。 'Char.IsDigit( '6');は' true'を返します。 'int.Parse(" 6 ")'は例外をスローします*;より正確なテストは 'c> = '0' && c <= '9''です。 –

0

私はそのようにそれを行うだろう:

var intArr = 
    orders.Split(new[] { ' ' }, StringSplitOptions.None) 
      .Select(q => 
        { 
         int res; 
         if (!Int32.TryParse(q, out res)) 
          return (int?)null; 
         return res; 
        }).Where(q => q.HasValue).ToArray(); 
-1
int[] results = orders.Split(' ').Where(s => s.ToCharArray().All(c => Char.IsDigit(c))) 
    .Select(s => Int32.Parse(s)).ToArray(); 
0

この文字列から整数を抽出します:

var numbers = 
    Regex.Split(orders, @"\D+") 
     .Where(x => x != string.Empty) 
     .Select(int.Parse).ToArray(); 

出力

numbers[0] == 2222 
numbers[1] == 1233 
numbers[2] == 222 
関連する問題