Clearing strings in C #

I am trying to write a function that, when an input takes a string containing words, and removes all single character words and returns a new string without deleted characters

eg:.

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

Can you help?

+3
source share
5 answers

I am sure it is better to use regex, but you can do the following:

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();
+3
source

Mandatory Single Line LINQ:

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

Or as a more convenient extension method:

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);
    }
}
+6
source

, , .

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

Linq -

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

Source: https://habr.com/ru/post/1757302/


All Articles