如何检查字符串是否有换行符,然后执行某些操作

时间:2015-06-01 16:50:59

标签: c# windows string

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

怎么可能?

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);

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

您的问题包含以下内容:

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

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();
    }
}