1

C#:

string mystring = "Hello World. & my name is < bob >. Thank You."
Console.Writeline(mystring.ToUpper())

I am trying to get all the text to be uppercase except--

&  <  > 

Because these are my encoding and the encoding wont work unless the text is lower case.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Dev
  • 1,780
  • 3
  • 18
  • 46

1 Answers1

1

You may split the string with a space, turn all the items not starting with & to upper and just keep the rest as is, and then join back into a string:

string mystring = "Hello World. & my name is < bob >. Thank You.";
string result = string.Join(" ", mystring.Split(' ').Select(m => m.StartsWith("&") ? m : m.ToUpper()));

enter image description here

Another approach is to use a regex to match &, 1+ word chars and then a ;, and match and capture other 1+ word char chunks and only turn to upper case the contents in Group 1:

var result = System.Text.RegularExpressions.Regex.Replace(mystring, 
    @"&\w+;|(\w+)", m => 
           m.Groups[1].Success ? m.Groups[1].Value.ToUpper() :
           m.Value
);
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Thank you! I was just about to ask you if there is a way of doing it without Linq because I am using a cut down version of c# in another Software. The second aproach works perfectly well. – Dev Jan 03 '17 at 15:14
  • The second option is using a Match evaluator. You may also define a separate method and pass it instead of the lambda expression. – Wiktor Stribiżew Jan 03 '17 at 15:16