1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
using System;
using System.Text.RegularExpressions;
namespace gfoidl.Tools
{
public static class StringExtensions
{
// Für bessere Leistung werden die Regex hier erstellt:
private static readonly Regex _regexInt = new Regex(@"\d+");
private static readonly Regex _regexDouble = new Regex(
@"\d+(" +
System.Globalization.NumberFormatInfo
.CurrentInfo.NumberDecimalSeparator +
@")?(\d+)*");
//---------------------------------------------------------------------
/// <summary>
/// Konvertiert eine Zeichenfolge in eine Ganzzahl
/// </summary>
/// <param name="s">
/// Zu konvertierender String (zB "123456" oder "text123456BlaBlaBla")
/// </param>
/// <returns>
/// Ganzahlrepräsentation der Zeichenfolge
/// </returns>
/// <remarks>
/// Zum Finden der Zahl im Text werden reguläre Ausdrücke verwendet
/// </remarks>
public static int? Str2Int(this string s)
{
if (string.IsNullOrEmpty(s))
return null;
else
{
int i;
if (int.TryParse(_regexInt.Match(s).Value, out i))
return i;
else
return null;
}
}
//---------------------------------------------------------------------
/// <summary>
/// Konvertiert eine Zeichenfolge in eine Dezimalzahl unabhängig
/// vom Dezimaltrennzeichen
/// </summary>
/// <param name="s">
/// Zu konvertierender String (zB "123.456" oder "123,456")
/// </param>
/// <returns>
/// Dezimalrepräsentation der Zeichenfolge
/// </returns>
public static double? Str2Double(this string s)
{
if (string.IsNullOrEmpty(s))
return null;
else
{
double d;
string tmp = s.Replace(
".",
System.Globalization.NumberFormatInfo
.CurrentInfo.NumberDecimalSeparator);
tmp = _regexDouble.Match(tmp).Value;
if (double.TryParse(tmp, out d))
return d;
else
return null;
}
}
//---------------------------------------------------------------------
public static DateTime? Str2Date(this string s)
{
if (string.IsNullOrEmpty(s))
return null;
else
{
DateTime d;
if (DateTime.TryParse(s, out d))
return d;
else
return null;
}
}
}
}
|