1

I am trying to write a code fragment in VB.net that selects the first alphabet of every word in a string and concatenates them. For example - "Concepts Of Computer Programming" should yield "COCP" as an output. Although I am acquainted with "myString.ToCharArray" and "string.Split" function but still not able to build the suitable logic. Kindly help me with it.

user3806216
  • 17
  • 1
  • 5

2 Answers2

0

You can use String.Split to split every word by white-spaces (doesn't take care of commas, semicolons, dots etc. but only spaces, tabs and new-line characters). Then you can use String.Concat to concat each character which you can extract with Enumerable.Select:

string text = "Concepts Of Computer Programming";
string[] words = text.Split(new char[]{}, StringSplitOptions.RemoveEmptyEntries); // tabs, spaces, new-lines
var firstChars = words.Select(w => w[0]);
string result = String.Concat( firstChars );

If you want to include other delimiters you can specify them explicitly:

char[] wordSeparators = = new[] { ' ','\t', ',', '.', '!', '?', ';', ':' };
string[] words = text.Split(wordSeparators, StringSplitOptions.RemoveEmptyEntries);
// ...

VB.NET (first snippet):

Dim text = "Concepts Of Computer Programming"
Dim words = text.Split(new char(){}, StringSplitOptions.RemoveEmptyEntries)
dim firstChars = from w in words Select w(0)
dim result = String.Concat( firstChars )
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

You Could also use this:

        Dim Final As String = Nothing
    Dim input As String = "Concepts Of Computer Programming"
    For Each word As String In input.Split(" ")
        Final = (Final & word(0))
    Next

I haven't been using vb.net for long and started learning it not long ago, so my method might be amateur compared to some but it gets the job done.

You could even set it up as a function like so:

    Public Function gather_initials(ByRef input As String) As String
    Dim Final As String = Nothing
    For Each word As String In input.Split(" ")
        Final = (Final & word(0))
    Next
    Return Final
End Function

and call it like so:

Dim ret As String = gather_initials("Concepts Of Computer Programming")
user1931470
  • 193
  • 1
  • 6