Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shortest way to get first char from every word in a string

Tags:

string

c#

split

I want a shortest way to get 1st char of every word in a string in C#.

what I have done is:

string str = "This is my style";
string [] output = str.Split(' ');
foreach(string s in output)
{
   Console.Write(s[0]+" ");
}

// Output
T i m s

I want to display same output with a shortest way...

Thanks

like image 715
Javed Akram Avatar asked Jan 17 '11 13:01

Javed Akram


People also ask

How do you get the first character of each word in a string?

To get the first letter of each word in a string: Call the split() method on the string to get an array containing the words in the string. Call the map() method to iterate over the array and return the first letter of each word. Join the array of first letters into a string, using the join() method.

How do you get the first character of a word in a string python?

Get the first character of a string in python As indexing of characters in a string starts from 0, So to get the first character of a string pass the index position 0 in the [] operator i.e. It returned a copy of the first character in the string. You can use it to check its content or print it etc.

Which of the following function operates on first character of each word of the string?

The strchr() function finds the first occurrence of a character in a string. The character c can be the null character (\0); the ending null character of string is included in the search. The strchr() function operates on null-ended strings.


1 Answers

var firstChars = str.Split(' ').Select(s => s[0]);

If the performance is critical:

var firstChars = str.Where((ch, index) => ch != ' ' 
                       && (index == 0 || str[index - 1] == ' '));

The second solution is less readable, but loop the string once.

like image 115
Cheng Chen Avatar answered Oct 07 '22 01:10

Cheng Chen