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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With