Chris
Chris

Reputation: 7611

C# - if statements against parts of a string

I basically want to check if part of a string begins with a certain sequence - in this case ftp://, or http://. How would I do this?

Thanks

Upvotes: 0

Views: 721

Answers (6)

Andy Rose
Andy Rose

Reputation: 16984

  if(myString.StartsWith("ftp://") || myString.StartsWith("http://")) { }  

if you wish it to ignore case then use StringComparison.OrdinalIgnoreCase.

  if(myString.StartsWith("ftp://", StringComparison.OrdinalIgnoreCase) || myString.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) { }  

Upvotes: 4

Mohamad Alhamoud
Mohamad Alhamoud

Reputation: 4929

String.StartsWith Method

Upvotes: 1

Polyfun
Polyfun

Reputation: 9639

You should use the String.StartsWith method.

Upvotes: 0

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60694

if( myString.StartsWith("ftp://")){
  ...
}

Similar if you want to check for http://, but change the parameter to StartsWith.

Upvotes: 1

riffnl
riffnl

Reputation: 3183

Personally I'd suggest use Regex, but the most basic form is

string myText = @"http://blabla.com";
if (myText.IndexOf("http://") == 0 || myText.IndexOf("ftp://") == 0))
{
//dosome
}

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838336

Use String.StartsWith. With just two possible prefixes you can write it as follows:

if (s.StartsWith("http://") || s.StartsWith("ftp://")) { ... }

If you have a lot of different possible prefixes it might be better to use a loop or a LINQ expression instead. For example:

string[] prefixes = { "http://", "ftp://", /* etc... */ };
if (prefixes.Any(prefix => s.StartsWith(prefix)))
{
    // ...
}

Upvotes: 12

Related Questions