19

I'm trying to remove the lower case letters on a TextBox..

For example, short alpha code representing the insurance (e.g., 'BCBS' for 'Blue Cross Blue Shield'):

txtDesc.text = "Blue Cross Blue Shield";

string Code = //This must be BCBS.. 

Is it possible? Please help me. Thanks!

abatishchev
  • 98,240
  • 88
  • 296
  • 433
im useless
  • 7,151
  • 7
  • 35
  • 49
  • 11
    What if the user enters "BLUE CROSS BLUE SHIELD", or worse "blue cross blue shield"? – Raghu Jun 09 '11 at 12:36

11 Answers11

39

Well you could use a regular expression to remove everything that wasn't capital A-Z:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main( string[] args )
    {
        string input = "Blue Cross Blue Shield 12356";
        Regex regex = new Regex("[^A-Z]");
        string output = regex.Replace(input, "");
        Console.WriteLine(output);
    }
}

Note that this would also remove any non-ASCII characters. An alternative regex would be:

Regex regex = new Regex(@"[^\p{Lu}]");

... I believe that should cover upper-case letters of all cultures.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 3
    Maybe `new Regex("...", RegexOptions.Compiled)`? – abatishchev May 23 '11 at 06:02
  • 2
    @abatishev - the compilation takes extra time, you don't want that on a local regex that's used once. – Hans Kesting May 23 '11 at 06:04
  • 1
    Actually it should be compiled and cached (or stored maybe in the static variable or sth) because creating new Regex every request MAY be a bit longer... but it is still such a micro optimization;) – luckyluke Jun 09 '11 at 19:35
21
string Code = new String(txtDesc.text.Where(c => IsUpper(c)).ToArray());
Andrew Cooper
  • 32,176
  • 5
  • 81
  • 116
  • I agree with this one with the addition of removing the spaces with either c => IsUpper(c) || c == ' ' or c => IsUpper(c) || IsWhiteSpace(c). – Almund May 23 '11 at 06:02
  • @Almund Why a whitespace check? –  May 23 '11 at 06:08
  • 1
    As it is, that won't work. It'll compile, then fail with a cast exception at execution time. You'd need something like `string code = new string(txtDesc.text.Where(c => IsUpper(c)).ToArray());` – Jon Skeet May 23 '11 at 06:08
  • Why does this fail since there is an explicit from `IEnumerable` to `string`? :( –  May 23 '11 at 06:11
  • @Almund - Why would you want the predicate to return `true` for whitespace. The idea is to only return characters from the sequence which are upper-case characaters. `.Where(c => IsUpper(c))` will do just that. – Andrew Cooper May 23 '11 at 06:11
  • I bow to the wisdom of @Jon Skeet, and have edited my answer accordingly. ;-) – Andrew Cooper May 23 '11 at 06:17
  • string Code = //This must be BCBS.. And his input example is "Blue Cross Blue Shield", thus I thought he´d probably wanted to get rid of the whitespaces even if it wasn't mentioned. – Almund May 23 '11 at 06:26
  • @Almund - Yes. And my Linq expression does get rid of whitespace. The resulting string only includes upper-case characters. – Andrew Cooper May 23 '11 at 06:28
  • @pst: There's an *explicit* cast available which makes it compile - but it would fail at execution time because it *isn't* a string. – Jon Skeet May 23 '11 at 06:31
12

Here is my variant:

var input = "Blue Cross Blue Shield 12356";
var sb = new StringBuilder();
foreach (var ch in input) {
  if (char.IsUpper(ch)) { // only keep uppercase
    sb.Append(ch);
  }
}
sb.ToString(); // "BCBS"

I normally like to use regular expressions, but I don't know how to select "only uppercase" in them without [A-Z] which will break badly on characters outside the English alphabet (even other Latin characters! :-/)

Happy coding.


But see Mr. Skeet's answer for the regex way ;-)

7

Without Regex:

string input = "Blue Cross Blue Shield";
string output = new string(input.Where(Char.IsUpper).ToArray());
Response.Write(output);
Barry Kaye
  • 7,682
  • 6
  • 42
  • 64
  • It's the same answer as @Andrew Cooper `string Code = new String(txtDesc.text.Where(c => IsUpper(c)).ToArray());` – manji Jun 10 '11 at 09:08
  • I disagree, it is similar but NOT the same: (1) @andrew-cooper answer does not compile (as commented by @jon-skeet) it should be Char.IsUpper. (2) `Char.IsUpper` is not the same as `c => Char.IsUpper(c)` as it replaces an anonymous method with a method group - see [link](http://stackoverflow.com/questions/2230451/c-method-group-strangeness) – Barry Kaye Jun 10 '11 at 10:56
5

You can try use the 'Replace lowercase characters with star' implementation, but change '*' to '' (blank)

So the code would look something like this:

txtDesc.Text = "Blue Cross Blue Shield";
string TargetString = txt.Desc.Text;
string MainString = TargetString;
for (int i = 0; i < TargetString.Length; i++)
{
    if (char.IsLower(TargetString[i]))
    {
        TargetString = TargetString.Replace( TargetString[ i ].ToString(), string.Empty );
    }
}
Console.WriteLine("The string {0} has converted to {1}", MainString, TargetString);
Community
  • 1
  • 1
abramlimpin
  • 5,027
  • 11
  • 58
  • 97
  • 2
    That needs to assign the result of the replace to something ;-) –  May 23 '11 at 06:01
  • `Replace` is not a member of TextBox :( –  May 23 '11 at 06:15
  • 1
    Not quite. `''` is an empty character literal, which is not allowed. [`string.Replace(string,string)`](http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx) would work (an empty string is quite allowed), but there is still a bug in the logic which yields an incorrect result. [LINQPad](http://www.linqpad.net/) is a neat tool to test out quick code. The bug has to do because some characters are skipped over -- the indexes are changed after the replace. –  May 23 '11 at 06:36
5

I´d map the value to your abbreviation in a dictionary like:

Dictionary<string, string> valueMap = new Dictionary<string, string>();
valueMap.Add("Blue Cross Blue Shield", "BCBS");

string Code = "";
if(valueMap.ContainsKey(txtDesc.Text))
  Code = valueMap[txtDesc.Text];
else
  // Handle

But if you still want the functionality you mention use linq:

string newString = new string(txtDesc.Text.Where(c => char.IsUpper(c).ToArray());
Almund
  • 5,695
  • 3
  • 31
  • 35
  • Your LINQ code doesn't compile and if even does - does the apposite thing. – abatishchev May 23 '11 at 06:04
  • Sorry! I hadn't double checked the syntax, the String.Join isn't to friendly with chars. Should work with new string() as it is now, otherwise look at Andrew Coopers answer. – Almund May 23 '11 at 06:28
  • Again look at Coopers answer, I had flipped the functionality to select all lowercase letters instead. – Almund May 23 '11 at 06:33
5
string Code = Regex.Replace(txtDesc.text, "[a-z]", "");
Chris Bricker
  • 318
  • 1
  • 3
5
string caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

string.Join("",
   "Blue Cross Blue Shield".Select(c => caps.IndexOf(c) > -1 ? c.ToString() : "")
                           .ToArray());
manji
  • 47,442
  • 5
  • 96
  • 103
3

Rather than matching on all capitals, I think the specification would require matching the first character from all the words. This would allow for inconsitent input but still be reliable in the long run. For this reason, I suggest using the following code. It uses an aggregate on each Match from the Regex object and appends the value to a string object called output.

string input = "Blue Cross BLUE shield 12356";
Regex regex = new Regex("\\b\\w");
string output = regex.Matches(input).Cast<Match>().Aggregate("", (current, match) => current + match.Value);
Console.WriteLine(output.ToUpper()); // outputs BCBS1
soniiic
  • 2,664
  • 2
  • 26
  • 40
  • P.s.s The Regex used in here uses \b which means word boundary and \w which means word character. A word character can be upper case or lower case or from any culture :) – soniiic Jun 09 '11 at 14:37
2
string Code = Regex.Replace(txtDesc.text, "[a-z]", "");
ghie
  • 567
  • 4
  • 11
  • 26
2

This isn't perfect but should work (and passes your BCBS test):

private static string AlphaCode(String Input)
{
    List<String> capLetter = new List<String>();
    foreach (Char c in Input)
    {
        if (char.IsLetter(c))
        {
            String letter = c.ToString();
            if (letter == letter.ToUpper()) { capLetter.Add(letter); }
        }
    }
    return String.Join(String.Empty, capLetter.ToArray());
}

And this version will handle strange input scenarios (this makes sure the first letter of each word is capitalized).

private static string AlphaCode(String Input)
{
    String capCase = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Input.ToString().ToLower());

    List<String> capLetter = new List<String>();
    foreach (Char c in capCase)
    {
        if (char.IsLetter(c))
        {
            String letter = c.ToString();
            if (letter == letter.ToUpper()) { capLetter.Add(letter); }
        }
    }
    return String.Join(String.Empty, capLetter.ToArray());
}
Jon
  • 150
  • 3