Home > OS >  How to get only the first letter of the first 2 words of a long string?
How to get only the first letter of the first 2 words of a long string?

Time:01-15

I have a long string name. Example: "Ahmet Enes Söylemez". I want to get only "AE" letters from this array. How can I do it ?

@{ string result = string.Concat(kullanici.AdSoyad.Where(char.IsUpper));
@result
 }

CodePudding user response:

You're almost there: Just .Take(2)

string result = string.Concat(kullanici.AdSoyad.Where(char.IsUpper).Take(2));

CodePudding user response:

I suggest using Regular Expressions here and match these two words. If we assume that the word of interes must start from capital letter and must continue with low case leters we can implement it it like this:

using System.Linq;
using System.Text.RegularExpressions;

...

string text = "Ahmet Enes Söylemez";

string letters = string.Concat(Regex 
  .Matches(text, @"\p{Lu}\p{Ll} ") // match each word of interest
  .Cast<Match>()
  .Take(2)       // We want just two first matches
  .Select(match => match.Value[0])); // Initial letters from each match

Here we use \p{Lu}\p{Ll} which is

\p{Lu}  - capital letter
\p{Ll}  - followed by one or more low case letters

Fiddle

CodePudding user response:

You can extract the first letter of each word in the string by using the split() and map() methods in JavaScript. The split() method can be used to split the string into an array of words, and the map() method can be used to extract the first letter of each word. Here's an example:

let name = "Ahmet Enes Söylemez";
let initials = name.split(" ").map(word => word[0]).join("").toUpperCase();
console.log(initials); // Output: "AES"

In this example, the split() method is used to split the string into an array of words using a space as the delimiter. Then the map() method is used to extract the first letter of each word in the array and return a new array of letters. The join() method is used to join the array of letters into a single string. Finally, the toUpperCase() method is used to convert the string to uppercase letters.

You can also use the same method but instead of join() method, you can use the slice() method with the index parameter to get the first two letters

let name = "Ahmet Enes Söylemez";
let initials = name.split(" ").map(word => word[0]).slice(0,2).join("").toUpperCase();
console.log(initials); // Output: "AE"

In this case, the slice() method is used to get the first two letters from the array of letters created with the map() method

Keep in mind that this example only takes the first letter of each word. If you want to get the first two letters, you can use word.slice(0,2) instead of word[0] in the map() method.

  • Related