比较String并省略空行?

时间:2013-08-11 00:28:30

标签: c# string compare

我有两个字符串,需要比较它们而不检查空行......

第一个字符串

CREATE OR REPLACE PROCEDURE "HELL_" 
as
begin
  dbms_output.put_line('Hello!');
end;

第二个字符串

CREATE OR REPLACE PROCEDURE "USER1"."HELL_" 
as

begin

  dbms_output.put_line('Hello!');

end;

我正在使用的代码:

                string text1 = "";
                string text2 = "";
                if (text1.Equals(text2 ))
                    MessageBox.Show("same");
                //no Exception
                else
                {
                    MessageBox.Show("not");
                }

3 个答案:

答案 0 :(得分:1)

您可以使用StringSplitOptions.RemoveEmptyEntries拆分行。生成的string[]不包含空行。然后Enumerable.SequenceEqual很有用。

string[] lines1 = text1.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
string[] lines2 = text2.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
bool equal = lines1.SequenceEqual(lines2);

如果“空”行可以包含空格:

var lines1 = text1.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
    .Where(l => l.Trim().Length > 0); 
var lines2 = text2.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
    .Where(l => l.Trim().Length > 0);

如果你想忽略空格:

var lines1 = text1.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
    .Where(l => l.Trim().Length > 0)
    .Select(l => l.Trim()); 
var lines2 = text2.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
    .Where(l => l.Trim().Length > 0)
    .Select(l => l.Trim()); 

如果您还想忽略这种情况:

bool equal = lines1.SequenceEqual(lines2, StringComparer.OrdinalIgnoreCase);

答案 1 :(得分:0)

与其他答案一样(通过首先“清理”),但更一般地将“空行”视为由CR,LF或两者的任意组合限定的任何仅限空格的行。

string RemoveEmptyLines (string s) {
    return Regex.Replace(s, @"(?:^|[\r\n]+)\s*?(?=(?:[\r\n]+|$))", "");
}

// Usage
RemoveEmptyLines(a) == RemoveEmptyLines(b)

可以根据需要扩展或细化行尾字符(即[\r\n])。此正则表达式一次只处理一个空行(尽管所有空白行将在单个Replace调用中删除),并使用非贪心量词和前向前瞻。我发现这种变化更明确地显示了预期的操作。

答案 2 :(得分:0)

对于您的具体情况,这可以解决问题:

         if (firststring.Equals(secondstring.Text.Replace("\r\n\r\n", "\r\n")))
             MessageBox.Show("same");
         //no Exception
         else
         {
             MessageBox.Show("not");
         }
相关问题