2

I've tried to solve this for hours and absolutely don't understand what the compiler is doing here. I have strings that basically look like this:

"KL10124 Traitor #2 - +XX-+0.25 - More Stuff"

and need to read off the double '0.25' programmatically. Calling the string above s, the following two lines don't work:

string[] h = s.Split('-');
string h2 = h[2].Substring(1,h[2].Length - 2);
double d = Convert.ToDouble(h2);

The output if I display d is "25". I thought it might depend on the '.' resp ',' culture dependency, but if I insert

double d = Convert.ToDouble(h2.Replace('.',','));

it does not change a thing, the output is still "25".

But finally, if I do the brute force method as below I get the verbatim output "0,25" on the screen

double d;
string[] h = s.Split('-');
string h2 = h[2].Substring(1,h[2].Length - 2);
if (h2.Contains("."))
{
    string[] h3 = h2.Split('.');
    d = Convert.ToDouble(h3[0]) + Convert.ToDouble(h3[1])/100;
}
else
{
    d = Convert.ToDouble(h2);
}
return d;

Why exactly do the first two versions not work? The last bit of code cannot be the correct way to do this.

4

8 に答える 8

6

使ってみて

double d = Convert.ToDouble(h2, CultureInfo.InvariantCulture);

それ以外の

double d = Convert.ToDouble(h2);
于 2012-08-23T13:48:05.083 に答える
3

正規表現の方法を試してください:

string input = "KL10124 Traitor #2 - +XX-+0.25 - More Stuff";

Match match = Regex.Match(input, "^.*([0-9]+\\.[0-9]+).*$");

if (match.Success)
{
    double value = Convert.ToDouble(match.Groups[1].Value, CultureInfo.InvariantCulture);
    Console.Write(value);
}
于 2012-08-23T14:25:51.830 に答える
3

多くの人がすでに正規表現の使用について言及しています。正規表現にあまり慣れていない場合は、次のページが役立ちます。

http://txt2re.com/index-csharp.php3?s=%22KL10124%20Traitor%20%232%20-%20%2bXX-%2b0.25%20-%20More%20Stuff%22&-7

乾杯

于 2012-08-23T13:52:25.720 に答える
2
d = double.Parse(h2,CultureInfo.InvariantCulture);

変換操作の形式プロバイダーを不変に設定する必要があります。

于 2012-08-23T13:47:32.200 に答える
1

変換する前に h2 を確認する必要があります。小数点が含まれていないようです。Convert.ToDouble は、それが分数であることを知るために先頭の 0 が必要になる場合がありますが、確かではありません。

一般に、これは正規表現を使用するとはるかに簡単です。この回答を参照してください。

于 2012-08-23T13:48:24.657 に答える
1

次のような RegEx クエリを使用します。

^KL\d+ Traitor #\d \- \+XX\-\+(\d+\.\d+) \- .+

グループ化 (括弧内の式) によって結果が得られます。

サンドボックスを参照してください。

于 2012-08-23T13:50:33.757 に答える
0

最初のコード例で h2 を出力して、部分文字列の抽出が正しく行われているかどうかを確認します。

また、正規表現を使用して数値を抽出すると、より簡単になります。

于 2012-08-23T13:48:46.783 に答える
0

正規表現を使用

(?<=\+)([0-9\.])+
于 2012-08-23T13:52:39.083 に答える