"Left" Function Equivalent in C#

  • Thread starter Thread starter OutdoorGuy
  • Start date Start date
O

OutdoorGuy

Greetings,

I have a "newbie" question. I was wondering if there is anything in C#
that corresponds to VB's "Left" function? I simply want to retrieve the
leftmost characters of a string and I wasn't sure what the best way was
to do that.

Thanks in advance!
 
OutdoorGuy said:
Greetings,

I have a "newbie" question. I was wondering if there is anything in C#
that corresponds to VB's "Left" function? I simply want to retrieve the
leftmost characters of a string and I wasn't sure what the best way was
to do that.

string s = "12345";
string left_three_of_s = s.Substring(0, 3);
 
How about substring:

int i = 3;
string x = "abcdefg";

string y = x.Substring( 0, i );

y will equal the first 3 characters of x

Martin
 
OutdoorGuy said:
Greetings,

I have a "newbie" question. I was wondering if there is anything in C#
that corresponds to VB's "Left" function? I simply want to retrieve the
leftmost characters of a string and I wasn't sure what the best way was
to do that.

Thanks in advance!

In addition to the other replies, and using their substring answer to create
a utility method that performs the Left (although you can use the
VisualBasic reference and import it...)

public string Left(string Original, int Count)
{
// Can't remember if the Left function throws an exception in this case,
but for
// this method, we will just return the original string.
if (Original == null || Original == string.Empty || Original.Length <
Count) {
return Original;
} else {
// Return a sub-string of the original string, starting at index 0.
return Original.Substring(0, Count);
}
}

public string Right(string Original, int Count)
{
// same thing as above.
if (Original == null || Original == string.Empty || Original.Length <
Count) {
return Original;
} else {
// blah blah blah
return Original.Substring(Original.Length - Count);
}
}

btw, this is untested code :)

HTH,
Mythran
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top