您好我想從一個文件讀取整數例如我想從這樣的文件(0,0,0)讀取一個向量,我想保存每個參數,x = 0 y = 0 z = 0我如何拆分字符串並保存整數。我有一個閱讀程序,讀取整數,但問題出現在我有一個雙diggit整數時,程序沒有讀取正確的值。我的文本文件是這樣的:拆分不同字符之間的整數
:Cube.Attach(100,0,5);
:Tree.Attach(10,0,50);
:Plane.Attach(0,0,0);
:Terrain.Attach(0,0,0);
您好我想從一個文件讀取整數例如我想從這樣的文件(0,0,0)讀取一個向量,我想保存每個參數,x = 0 y = 0 z = 0我如何拆分字符串並保存整數。我有一個閱讀程序,讀取整數,但問題出現在我有一個雙diggit整數時,程序沒有讀取正確的值。我的文本文件是這樣的:拆分不同字符之間的整數
:Cube.Attach(100,0,5);
:Tree.Attach(10,0,50);
:Plane.Attach(0,0,0);
:Terrain.Attach(0,0,0);
您可以嘗試使用正規表達式,這樣的事情:
// 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)"
你在正則表達式沒有必要的情況下,因爲Split
和Trim
足夠:
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];
感謝您的回答,但不幸的是我只需要解析字符的整數,因爲我有一個工作程序,這是我需要解決的唯一問題,我認爲正則表達式是正確的答案。 – anthraxa
@anthraxa:如果你想解析整數,例如對於''(100,18,-125)''''你想有'[100,18,-125]'正則表達式是過沖的,只需要'Split'就可以完成(見我的編輯) –
要麼使用正則表達式或簡單的文件格式,其中每個v ector是在一個新的行中,數字由空格分開,這樣你可以簡單地使用'string.split'。無論哪種方式,對於更復雜的數據,您不應該使用txt文件。你最好使用XML。 – TheDjentleman
*「問題來了,當我有一個雙diggit整數」* - 哪個問題來了?例外?有些東西不起作用?你可以展示你的代碼,給出一些示例輸入並顯示產生的和期望的輸出嗎? – Sinatr
這是我必須使用的格式,因爲我的程序也在查看該方法是否存在附加在此示例中。我會嘗試正則表達式。謝謝你的回答 – anthraxa