Here is how I would write a function to make an acronym in Java style:
string makeAcronym(string str)
{
string result = \"\";
for (in
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();
}
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()
);
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]);
}
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()
)
string makeAcronym(string str)
{
return new string(str.Split(new [] {' '},
StringSplitOptions.RemoveEmptyEntries).Select(s => s[0]).ToArray());
}