快速从字符串中删除部分内容

时间:2014-03-24 10:40:11

标签: c# string

从以下字符串String1我想删除" am" 之前的所有内容以及" Uhr" 之后的所有内容

string String1 = "Angebotseröffnung am 27.03.2014, 11:00 Uhr, Ort: Vergabestelle, siehe a).";

所以最后我有这个字符串。 " am 27.03.2014,11:00 Uhr"

我正在使用此代码,但我知道这不是一个好方法。有人可以帮助我提供更好的选择。

String1 = String1.Replace("Angebotseröffnung", "");
String1 = String1.Replace("Ort", "");
String1 = String1.Replace("Vergabestelle", "");
String1 = String1.Replace("siehe", "");
String1 = String1.Replace("a)", "");

7 个答案:

答案 0 :(得分:3)

尝试这样的事情:

var string1 = "Angebotseröffnung am 27.03.2014, 11:00 Uhr, Ort: Vergabestelle, siehe a).";

var startIndex = string1.IndexOf("am"); // 18
var endIndex = string1.IndexOf("Uhr") + 3; // 42

// Get everything between index 18 and 42
var result = string1.Substring(startIndex, endIndex - startIndex); 

// result: "am 27.03.2014, 11:00 Uhr"

答案 1 :(得分:2)

另一种选择是使用Regex.Match。

string output = Regex.Match(String1, "am.*Uhr").Value;

但只有在字符串中肯定有amUhr时才会有用。 根据您的输入,您可能需要am.*?Uhr(?:a|p)m.*?Uhr正则表达式。

答案 2 :(得分:1)

如果格式严格且始终包含Angebotseröffnung amUhr,则效率最高:

string String1 = "Angebotseröffnung am 27.03.2014, 11:00 Uhr, Ort: Vergabestelle, siehe a).";
string result = null;
string startPattern = "Angebotseröffnung am ";
int start = String1.IndexOf(startPattern);
if (start >= 0)
{
    start += startPattern.Length;
    string endPattern = " Uhr";
    int end = String1.IndexOf(endPattern, start);
    if (end >= 0)
        result = String1.Substring(start, end - start + endPattern.Length);
}

答案 3 :(得分:0)

如果您知道格式将始终相同=>

var r = new Regex("am \d{1,2}.\d{1,2}.\d{4} Uhr");
var result = r.Match(input);

答案 4 :(得分:0)

如果字符串始终包含 am Uhr ,并且在 Uhr 之前始终 am :< / p>

string String1 = "Angebotseröffnung am 27.03.2014, 11:00 Uhr, Ort: Vergabestelle, siehe a).";

int indexOfAm = String1.IndexOf("am");
int indexOfUhr = String1.IndexOf("Uhr");

string final = String1.Substring(indexOfAm, (indexOfUhr + 3) - indexOfAm);

答案 5 :(得分:0)

使用StringBuilder,Replace的工作方式与字符串相同,但不需要分配结果

class Program
        {
            static void Main()
            {
        const string samplestring = "hi stack Over Flow String Replace example.";

        // Create new StringBuilder from string

                StringBuilder str = new StringBuilder(samplestring );



                // Replace the first word
                // The result doesn't need assignment
                str.Replace("hi", "hello");
                Console.WriteLine(b);
        }
        }

    Output Will be -->
    hello stack Over Flow String Replace example

答案 6 :(得分:0)

试试这个

  String1 = String1.Substring(String1.IndexOf("am"), (String1.IndexOf("Uhr") - String1.IndexOf("am"))+3);