C#中的字符串清理

时间:2010-07-30 09:07:31

标签: c# string

我正在尝试编写一个函数,当输入接受包含单词的字符串并删除所有单个字符单词并返回没有删除字符的新字符串

E.g:

string news = FunctionName("This is a test");
//'news' here should be "This is test".

你能帮忙吗?

5 个答案:

答案 0 :(得分:6)

强制性LINQ单线:

string.Join(" ", "This is a test".Split(' ').Where(x => x.Length != 1).ToArray())

或者作为更好的扩展方法:

void Main()
{
    var output = "This is a test".WithoutSingleCharacterWords();
}

public static class StringExtensions
{
    public static string WithoutSingleCharacterWords(this string input)
    {
        var longerWords = input.Split(' ').Where(x => x.Length != 1).ToArray();
        return string.Join(" ", longerWords);
    }
}

答案 1 :(得分:3)

我确信使用正则表达式有更好的答案,但您可以执行以下操作:

string[] words = news.Split(' ');

StringBuilder builder = new StringBuilder();
foreach (string word in words)
{
    if (word.Length > 1)
    {
       if (builder.ToString().Length ==0)
       {
           builder.Append(word);
       }
       else
       {
           builder.Append(" " + word);
       }
    }
}

string result = builder.ToString();

答案 2 :(得分:2)

关于这个问题的有趣之处在于,大概你也想删除单个字母单词周围空格的一个

    string[] oldText = {"This is a test", "a test", "test a"};
    foreach (string s in oldText) {

        string newText = Regex.Replace(s, @"\s\w\b|\b\w\s", string.Empty);
        WL("'" + s + "' --> '" + newText + "'");
    }

...输出

'This is a test' --> 'This is test'
'a test' --> 'test'
'test a' --> 'test'

答案 3 :(得分:0)

使用Linq语法,您可以执行类似

的操作
return string.Join(' ', from string word in input.Split(' ') where word.Length > 1))

答案 4 :(得分:0)

string str = "This is a test.";
var result = str.Split(' ').Where(s => s.Length > 1).Aggregate((s, next) => s + " " + next);

<强> UPD

使用扩展方法:

public static string RemoveSingleChars(this string str)
{
      return str.Split(' ').Where(s => s.Length > 1).Aggregate((s, next) => s + " " + next);       
}


//----------Usage----------//


var str = "This is a test.";
var result = str.RemoveSingleChars();