如何将字符串放在换行符中?

时间:2013-12-03 10:59:16

标签: c# .net line-breaks stringbuilder

我正在使用C#中的字符串。我有一个字符串,

StringBuilder sb = new StringBuilder();
sb.AppendLine(ValidatorMethod1());
sb.AppendLine(ValidatorMethod2());

ValidatorMethod1()上调用“sb”后,如图所示调用ValidatorMethod2(),两者都根据条件返回错误消息作为字符串。如果ValidatorMethod1()ValidatorMethod2()返回错误消息,则一切正常。但是如果ValidatorMethod2()失败,那么从ValidatorMethod2(返回的错误消息的长度是“0”,但仍然有一行附加“sb”,因此在{{{{}}之后附加一个空的错误行。 1}}的错误信息。

我尝试使用Google搜索,但链接如下:

所以请任何人都可以提出一个想法,“如果长度大于零,则将返回的字符串放在换行符中”或什么都不做?

编辑:

大家好,  我想我会得到适当的解决方案,我正在寻找。我不想在每个“sb”之后追加一行。但是,如果我有一个错误消息,那么,我想放入NEWLINE .. 有人可以给我一个满足我需要的不同解决方案吗?..

6 个答案:

答案 0 :(得分:5)

您可以String.IsNullOrEmpty查看结果的长度是否大于0

例如:

string result = ValidatorMethod2();
if (!String.IsNullOrEmpty(result))
   sb.AppendLine(result);

答案 1 :(得分:2)

你有什么理由不是自己检查一下吗?这几乎不会增加任何明显的开销:

StringBuilder sb = new StringBuilder();

String msg;

msg = ValidatorMethod1();
if (msg.Length > 0)
    sb.AppendLine(msg);

msg = ValidatorMethod2();
if (msg.Length > 0)
    sb.AppendLine(msg);

事实上,没有更快的方法。即使微软提供了一些内置功能,也不会有明显的不同。

答案 2 :(得分:0)

您可以将此代码用于每个验证器:

string error = null;

// repeat for each validator
error = ValidatorMethod1();
if (!String.IsNullOrEmpty(error)) sb.AppendLine(error);

答案 3 :(得分:0)

您可以尝试做类似的事情(如果sb包含任何文本,则在每个非空字符串之前调用AppendLine):

StringBuilder sb = new StringBuilder();

String message = ValidatorMethod1();

if (!String.IsNullOrEmpty(message))
  sb.Append(message);

message = ValidatorMethod2();

if (!String.IsNullOrEmpty(message)) {
  if (sb.Length > 0)
    sb.AppendLine();

  sb.Append(message);
}

一般情况下,当你有许多验证器时:

StringBuilder sb = new StringBuilder();

foreach(String result in getValidatorsResults()) {
  if (String.IsNullOrEmpty(result)) 
    continue;

  if (sb.Length > 0)
    sb.AppendLine();

  sb.Append(result);
}

答案 4 :(得分:0)

你可以这样做:

string sb1 = ValidatorMethod1();
string sb2 = ValidatorMethod2();
if (sb1 != "") sb.AppendLine(sb1);
if (sb2 != "") sb.AppendLine(sb2);

答案 5 :(得分:0)

如果您正在使用一组验证方法,您可能需要考虑这样的事情:

var validationMethods = new Func<string>[]
{
    () => ValidationMethod1(),
    () => ValidationMethod2(),
    // Add more validtion methods here
};
string error = string.Join(Environment.NewLine, validationMethods.Select(validationMethod => validationMethod()).Where(message=> !string.IsNullOrEmpty(message)));

如果您需要更改要在序列中运行的验证方法的数量,或者您甚至想要拥有动态数量的验证方法,那么此解决方案很容易扩展(那么您应该使用{{1而不是)。

相关问题