Here is how I would write a function to make an acronym in Java style:
string makeAcronym(string str)
{
string result = "";
for (int i = 0; i < str.Length; i++)
{
if (i == 0 && str[i].ToString() != " ")
{
result += str[i];
continue;
}
if (str[i - 1].ToString() == " " && str[i].ToString() != " ")
{
result += str[i];
}
}
return result;
}
Is there a more elegant way I can do it with LINQ, or using some built in C# function?
In order to check if a string S can be an acronym, first, we should decrease the frequency of the first letter of S then check if the frequency of every letter in S is less than or equal to its value in freq [] array.
To print the abbreviation of a text follow the following steps: Initialize an empty string (i.e. abbr). Append the first letter of string to abbr and also append a ‘ . ‘ to abbr.
The string length is less than 10. We will print all alphanumeric abbreviations. The alphanumeric abbreviation is in the form of characters mixed with the digits. The value of that digit is number of characters that are missed.
For example, csa is an acronym for the subset {computer, academy, science} ans so is acs. Print the number of strings that can be an acronym of other strings. Recommended: Please try your approach on {IDE} first, before moving on to the solution.
Here are a couple of options
A .NET 4 only option using string.Join:
string acronym = string.Join(string.Empty,
input.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries).Select(s => s[0])
);
In .NET 3.5 (or 4.0), you can do:
string acronym = new string(input.Split(new[] {' '},
stringSplitOptions.RemoveEmptyEntries).Select(s => s[0]).ToArray());
Another option (my personal choice), based on your original logic:
string acronym = new string(
input.Where( (c,i) => c != ' ' && (i == 0 || input[i-1] == ' ') )
.ToArray()
);
Here's a technique I haven't seen so far. It depends on the assumption that all the letters that should be in the acronym (and only those letters) are in upper-case in the string.
string MakeAcronym(string input)
{
var chars = input.Where(Char.IsUpper).ToArray();
return new String(chars);
}
// MakeAcronym("Transmission Control Protocol") == "TCP"
You can do this quite nicely using a Regex/Linq combo:
String
.Join("",
Regex
.Matches("this is a test",@"(?<=^| )\w")
.Cast<Match>()
.Select(m=>m.Value)
.ToArray()
)
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