- Home /
Get the upper Chars out of a string
Hey guys,
i need to get the upper characters out of a string. My method:
test = getUpperChars("ExampleText")
public string getUpperChars(string str)
{
var result = String.Concat(Regex
.Matches(str, "[A-Z]")
.OfType<Match>()
.Select(Match => Match.Value.ToString()));
Debug.Log(result);
return result;
}
I do not understand why this message gets back instead of a string with the content ("ET"):
System.Linq.Enumerable+c__Iterator10`2[System.Text.RegularExpressions.Match,System.String] UnityEngine.Debug:Log(Object)
Can anyone tell me what I am doing wrong? Thanks for the answers!
Answer by Bunny83 · Mar 18, 2018 at 12:51 AM
Well, depending on your Unity version and your used scripting backend Untiy will usually use Mono. The Mono version that Unity uses doesn't have this Concat overload. It only has Concat versions that take one or multiple "object" parameters. Of course Concat would simply call ToString on each parameter you pass in. Since the only thing you pass in is an IEnumerable instance (which is created from the Select method), that ToString will just return the type name of that IEnumerable which is what you see here.
You either need to use one of the Aggregate extensions to create a string or convert the IEnumerable into an Array and pass that to Concat
edit
Though all that usage of regular expressions, enumerables and string conversion will generate quite a bit of garbage. Since you really just want upper case letters something like that might be better:
public static void GetUpperCaseLetters(string aText, System.Text.StringBuilder aOutput)
{
for(int i = 0; i < aText.Length; i++)
{
char c = aText[i];
if (c > 'A' && c < 'Z')
aOutput.Append(c);
}
}
public static string GetUpperCaseLetters(string aText)
{
var sb = new System.Text.StringBuilder(aText.Length);
GetUpperCaseLetters(aText, sb);
return sb.ToString();
}
I splitted the method into two seperate methods as depending on the usecase you may want to reuse the string builder instance.
Your answer
Follow this Question
Related Questions
LINQ Find String Duplicates in List 1 Answer
Replace chars in String with a Dictionary and avoid order-sensitive problems 0 Answers
Creating a card game. Best ways to interpret the various cards? 1 Answer
Replace() with string and Regex not replacing numbers/integers 2 Answers
How to replace a word inside a string with different white space combos? 0 Answers