Is there any easy way to create an acronym from a string?
First_name Middle_name Last_name => FML
first_name middle_name last_name => FML
First_name-Middle_name Last_name => F-ML
first_name-middle_name last_name => F-ML
Is there any easy way to create an acronym from a string?
First_name Middle_name Last_name => FML
first_name middle_name last_name => FML
First_name-Middle_name Last_name => F-ML
first_name-middle_name last_name => F-ML
I don't know about language agnostic, but I would make a function that accepts an args[] parameter to bring in all of your strings then loop through those and concatenate the first char of each onto another string which is returned.
Edit: Strike that. Didn't realize it was a single string. You would have to loop through all characters looking for special character types. Any letters after the first would be ignored until you get to a space or special character.
Tokenize the string on whitespace.
For each token1,
Tokenize on dash.
For each token2
Take token2[0] and capitalize
if not first token2, prepend with dash
Concatenate to result2
Concatenate to result
Does language-agnostic means you have to use pseudocode? If not, then in Ruby:
"First_name-Middle_nameLast_name".gsub('-', ' - ').gsub(/\B[A-Z]+/, ' \&').split(' ').map { |s| s[0..0] }.join.upcase => "F-ML"
If it turns out the lack of space in the third example is a typo, you can skip the second call to gsub
(with the ugly regexp.)
Example in JavaScript, supposing the lack of space before Last in 3rd example is a typo:
var testStrings = [
'First_name Middle_name Last_name',
'first_name middle_name last_name',
'First_name-Middle_name Last_name',
'first_name-middle_name last_name'
];
var re = /\b(\w)\w*\b(-?)\s*/g;
var mr;
for (var i = 0, l = testStrings.length; i < l; i++)
{
var name = testStrings[i];
var abbr = name.replace(re, function (match, ini, dash)
{
return ini.toUpperCase() + dash;
});
alert(abbr);
}
Should be easy (?) to adapt to other languages.