Reputation: 122520
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?
Upvotes: 9
Views: 6432
Reputation: 120488
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()
)
Upvotes: 5
Reputation: 28764
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"
Upvotes: 8
Reputation: 564611
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()
);
Upvotes: 15
Reputation: 808
You can use the LINQ Aggregate method to do this in a fairly elegant way.
Something like this:
private static string MakeAcronym2(string str)
{
return str.Split(' ').Aggregate("", (x, y) => x += y[0]);
}
Upvotes: 4
Reputation: 755101
LINQ can work for this but generally I find it's better to build up string
values using StringBuilder
instance. This allows you to avoid unnecessary string
allocations.
string makeAcronym(string str) {
var builder = new StringBuilder();
for ( var i = 0; i < str.Length; i++ ) {
var c = str[i];
if ( c == ' ' ) {
continue;
}
if ( i == 0 || str[i-1] == ' ' ) {
builder.Append(c);
}
}
return builder.ToString();
}
Upvotes: 2
Reputation: 68707
string makeAcronym(string str)
{
return new string(str.Split(new [] {' '},
StringSplitOptions.RemoveEmptyEntries).Select(s => s[0]).ToArray());
}
Upvotes: 0