Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

most elegant way to remove string element

Tags:

string

c#

I'm fetching string from output file which will always be either Ok or Err. After that I'm casting this result Ok or Err to Enum property, which is ok, everything works, but I'm sure that there must be a better way than mine.

Since I'm fetching 3 characters in case that Ok is fetched I need to remove third element from Ok; result.

string message = File.ReadAllText(@"C:\Temp\SomeReport.txt").Substring(411, 3);
 if (message == "Ok;") // `;` character should be removed in case that Ok is fetched
 {
    message = "Ok";
 }

Thanks

like image 718
user1765862 Avatar asked Dec 22 '12 08:12

user1765862


3 Answers

You could just use String.Trim() to remove the ';' if its there.

string message = File.ReadAllText(@"C:\Temp\SomeReport.txt").Substring(411, 3).TrimEnd(';')

Result:

"Err" = "Err"
"Ok;" = "Ok"
like image 83
sa_ddam213 Avatar answered Oct 30 '22 07:10

sa_ddam213


You can just do this:

switch (message)
{
  case "Err":
    SomeProperty = EnumName.Err;
    break;

  case "Ok;":
    SomeProperty = EnumName.Ok;
    break;

  default:
    throw new Exception("Unexpected file contents: " + message);
}

If you don't like that, you can use TryParse after trimming the semicolon:

EnumName result;
if (Enum.TryParse(message.TrimEnd(';'), out result))
  SomePropery = result;
else
  throw new Exception("Unexpected file contents: " + message);
like image 43
Jeppe Stig Nielsen Avatar answered Oct 30 '22 07:10

Jeppe Stig Nielsen


     Enum message = Enum.Err;
     if (Regex.Match(File.ReadAllText(@"C:\Temp\SomeReport.txt"), "(ok.+?){3}", RegexOptions.Singleline).Success)
     {
        message = Enum.OK;
     }
like image 25
VladL Avatar answered Oct 30 '22 07:10

VladL