tags:

views:

1443

answers:

5

Hi all,

I'm using substring and IndexOf to locate a value within a string but my code doesn't work if the string (strOldValue) below contains any of the string in a different case. So if strOldValue contained Test or TEST then my substring fails. How would I add ToUpper in this scenario? Forgive my ignorance I'm new to .Net.

String strValue = strOldValue.Substring(strOldValue.IndexOf(@"test"));

Thanks C

+3  A: 
String strValue 
    = strOldValue.Substring(strOldValue.ToUpper().IndexOf(@"TEST"));

Note: I'm answering the question directly as asked ("How would I add ToUpper in this scenario?").

This is NOT how I would code a case-insensitive substring.

The answer by divo/TheSoftwareJedi is clearly superior.

Portman
Note: I'm answering the question directly as asked ("How would I add ToUpper in this scenario?"). This is NOT how I would code a case-insensitive substring.
Portman
Perhaps putting how you would code it would help. Sometimes the n00b questions aren't asked perfectly you know ;)
TheSoftwareJedi
The answer by divo/TheSoftwareJedi is clearly superior.
Portman
+16  A: 

Using ToUpper, it would be done like this:

String strValue = strOldValue.Substring(
                    strOldValue.ToUpper().IndexOf(@"TEST"));

However, the easiest would be to specify that the comparison should not be done case-sensitive:

String strValue = strOldValue.Substring(strOldValue.IndexOf(@"TEST",
          StringComparison.CurrentCultureIgnoreCase));

The second comparisonType parameter of the IndexOf method specifies how to search for the value parameter: using the current or invariant culture, using a case-sensitive or case-insensitive search, or using word or ordinal comparison rules (see http://msdn.microsoft.com/en-us/library/ms224425.aspx for the full documentation).

0xA3
I'm merging my answer with yours. If you don't like it, roll it back. I think ours combined is the best
TheSoftwareJedi
I edited to avoid Horizontal scroll bars - please rollback if you don't like .
Charles Bretana
Ooh that's better :)
Kev
Thanks for all the edits!
0xA3
+1  A: 
strValue.Substring(strValue.IndexOf("TEST", StringComparison.OrdinalIgnoreCase));
ccook
A: 

As an regular expressions fan, I would use the following code:

String strValue = new Regex("test.*",
       RegexOptions.IgnoreCase).Match(strOldValue).Value;
Jader Dias
+1  A: 

Using the String.IndexOf(String,StringComparison) is probably the best answer. Using ToUpper() in there someplace just creates an extra String object that has to be destroyed by GC. Almost all the String comparison methods have an overload that accepts a flag that states how to do comparisons.

Doug Boone