【问题标题】:how to check if a string has a newline,then do something如何检查字符串是否有换行符,然后做一些事情
【发布时间】:2015-08-15 05:37:43
【问题描述】:

我有这段代码,它将反转文本输入。它不捕获换行符,所以我想检查每次我们是否遇到换行符,以便在我的结果字符串中手动插入换行符。

这怎么可能?

var a = textBox1.Text;
var c = Environment.NewLine;
string b = "";
foreach(var ch in a)
{
   if (ch.ToString() ==c)
      b += c;
   else
      b = ch + b;
   b += "\n";
}
textBox2.Text = b;
Clipboard.SetText(b);

【问题讨论】:

标签: c# windows string


【解决方案1】:

您的问题包含以下组成部分:

  • 如何将字符串分成几行(处理换行符可能表示为\n\r\n 的事实)。
  • 如何反转给定的行,正确处理 unicode 复杂性,包括 surrogate pairs and combining characters

以下扩展方法处理这两个任务:

public static class TextExtensions
{
    public static IEnumerable<string> TextElements(this string s)
    {
        // StringInfo.GetTextElementEnumerator is a .Net 1.1 class that doesn't implement IEnumerable<string>, so convert
        if (s == null)
            yield break;
        var enumerator = StringInfo.GetTextElementEnumerator(s);
        while (enumerator.MoveNext())
            yield return enumerator.GetTextElement();
    }

    public static string Reverse(this string s)
    {
        if (s == null)
            return null;
        return s.TextElements().Reverse().Aggregate(new StringBuilder(s.Length), (sb, c) => sb.Append(c)).ToString();
    }

    public static IEnumerable<string> ToLines(this string text)
    {
        // Adapted from http://stackoverflow.com/questions/1508203/best-way-to-split-string-into-lines/6873727#6873727
        if (text == null)
            yield break;
        using (var sr = new StringReader(text))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                yield return line;
            }
        }
    }

    public static string ToText(this IEnumerable<string> lines)
    {
        if (lines == null)
            return null;
        return lines.Aggregate(new StringBuilder(), (sb, l) => sb.AppendLine(l)).ToString();
    }

    public static string ReverseLines(this string s)
    {
        if (s == null)
            return null;
        return s.ToLines().Reverse().Select(l => l.Reverse()).ToText();
    }
}

【讨论】:

    【解决方案2】:

    您可以使用Split 获取所有行,然后反转每一行。

    String a = textBox1.Text;
    String result = String.Empty;
    
    String[] lines = a.Split(new String[] { Environment.NewLine }, StringSplitOptions.None);
    
    foreach(String line in lines.Reverse())
    {
        // inverse text
        foreach(char ch in line.Reverse())
        {
            result += ch;
        }
    
        // insert a new line
        result += Environment.NewLine;
    }
    
    // remove last NewLine
    result = result.Substring(0, result.Length - 1);
    

    示例:在条目中,如果您有:

    test
    yopla
    

    结果将是:

    alpoy
    tset
    

    【讨论】:

      猜你喜欢
      • 2011-05-24
      • 2017-09-23
      • 1970-01-01
      • 2012-01-26
      • 2015-03-18
      • 2011-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多