views:

105

answers:

6

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

+12  A: 

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)))
{
    // ...
}
Mark Byers
Nice use of LINQ
Andy Rose
seconded... Appreciate the use of LINQ here
Xander
+4  A: 
  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)) { }  
Andy Rose
If wish it to ignore case, it would be better to use: myString.StartsWith("ftp://", StringComparison.OrdinalIgnoreCase);
Dylan Lin
@Dylan - quite right in this scenario, I will update the answer.
Andy Rose
A: 

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
}
riffnl
Wouldn't Regex be less performant than StartsWith/IndexOf?
Øyvind Bråthen
@Øyvind, in this case it probably would, but in a more general case it could well be more performant, depending on the complexity of the test required.
Jon Hanna
true; performance will drop, but ussually you start with.. I want to know of http is a part of the string.. and you end with: I need to know if the url is valid
riffnl
+1  A: 
if( myString.StartsWith("ftp://")){
  ...
}

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

Øyvind Bråthen
A: 

You should use the String.StartsWith method.

ShellShock
A: 

String.StartsWith Method

M.H