[英]Convert string to array of Uint16
新年快樂 !
我從 OPC UA 服務器收集了數據,數據是:
0;0;0;0;0;
我需要將此數據寫入我的 OPC UA 服務器,良好的語法必須是:
UInt16[] temp = { 0, 0, 0, 0, 0 };
如何將第一個字符串轉換為我的 Uint16 數組?
使用String.Split()
方法拆分 String 后,可以使用 try-catch 塊內的Convert.ToUInt16()
方法安全地將String
數據轉換為UInt16
類型。 開發的 static 方法如下:
public static UInt16[] Convert(String[] values)
{
UInt16[] numbers = new UInt16[values.Length - 1];
try
{
for(int i = 0 ; i < values.Length - 1 ; ++i)
numbers[i] = System.Convert.ToUInt16(values[i]);
}
catch(FormatException){}
return numbers;
}
public static void Print(UInt16[] numbers)
{
for(int index = 0 ; index < numbers.Length ; ++index)
System.Console.WriteLine("[{0}]: {1}", index, numbers[index]);
}
下面是調用 static 方法的應用程序:
String[] values= "1;2;3;4;5;".Split( ';' );
uint size = (uint)values.Length - 1;
UInt16[] numbers = new UInt16[size];
numbers = Convert(values);
Print(numbers);
該程序產生以下 output:
[0]: 1
[1]: 2
[2]: 3
[3]: 4
[4]: 5
假設
var s = "0;0;0;0;0;";
嘗試這個
UInt16[] temp = s.Split( ";" , StringSplitOptions.RemoveEmptyEntries)
.Select(p => Convert.ToUInt16(p)).ToArray();
謝謝大家,最后它正在處理這個:
string data = childNode.InnerXml; //0;0;0;0;0;
string[] words = data.Split(';').SkipLast(1).ToArray(); //need to remove the last empty element of the array
UInt16[] myInts = Array.ConvertAll(words, s => UInt16.Parse(s));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.