2010-07-30 68 views
3

我想编写一个函数,输入需要包含单词串并删除所有单个字符单词,并返回新的字符串,而不删除字符字符串清理在C#中

如:

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

你能帮忙吗?

+3

如果你正在做大量的字符串处理,避免正则表达式。这是球慢。我会选择非正则表达式解决方案作为更好的答案。 – 2010-07-30 09:13:48

+0

你可以将它作为字符串的扩展方法来实现,以便于阅读。 – Peter 2010-07-30 09:17:03

回答

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

关于这个问题的有趣的事情是,想必你也想去掉周围的空间一个单字母单词。

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' 
+0

我刚刚达到这一点。然后我开始考虑以单个字符开始和结尾的字符串,并且我的脑袋开始受到伤害:) – MPritchard 2010-07-30 09:18:52

+0

至少,将正则表达式从循环中移出以实现更高的性能(tm);) – 2010-07-30 11:19:16

+0

为了清晰起见,使用最优化编码以作为为读者提供练习;-) – 2010-07-30 11:25:06

0

LINQ的语法,你可以不喜欢

return string.Join(' ', from string word in input.Split(' ') where word.Length > 1)) 
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); 
    } 
} 
+0

+1喜欢使用扩展方法,并且比我的示例清洁多少。我必须正确学习LINQ。 – GenericTypeTea 2010-07-30 09:41:52

+0

如果单词之间有不同的空格,该怎么办? – Grzenio 2010-07-30 10:24:41

+0

@Grzenio你可以使用Regex.Split(input,@“\ s”)来代替,如果你想捕捉标签和换行符。我只是从问题中通过测试用例:) – 2010-07-30 11:14:31

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