How do I: Extract the last 3 characters of a string

  • Thread starter Thread starter SamIAm
  • Start date Start date
S

SamIAm

How do I extract the last 3 characters of a string i.e.

string s = "000001" I want "001"

Thanks,

S
 
SamIAm, you can use s.SubString() to extract any portion of a string.
You'll also probably want to use s.Length - 3 for your start position.

--
Greg Ewing [MVP]
http://www.citidc.com


How do I extract the last 3 characters of a string i.e.

string s = "000001" I want "001"

Thanks,

S
 
SamIAm said:
How do I extract the last 3 characters of a string i.e.

string s = "000001" I want "001"

Probably overkill for your current problem, but you can use an Regular
Expression [RE] to select the part of the string that you want, in this
case, it would be @".{3}$". You would be amazed at what can be accomplished
with RE's ! Below is some sample code, though I'd recommend you consult the
relevant documentation and a tutorial or two :) !

I hope this helps.

Anthony Borla

using System;
using System.Text.RegularExpressions;

public class RegexExample
{
public static void Main()
{
String str = "000001";

Regex re = new Regex(@".{3}$", RegexOptions.None);

MatchCollection mlist = re.Matches(str);

if (mlist.Count > 0)
Console.WriteLine("str = {0}, match = {1}", str, mlist[0].Value);
else
Console.WriteLine("No match!");

String substr = mlist[0].Value.ToString();
}
}
 
Thanks for all the replies
How do I extract the last 3 characters of a string i.e.

string s = "000001" I want "001"

Thanks,

S
 
string temp = "";
string s = "000001";

for (int i = s.Length - 3; i < s.Length ; i++)
{
temp += s; // the three characters you're looking for
// are now in the string 'temp';
}

How do I extract the last 3 characters of a string i.e.
string s = "000001" I want "001"

Hope that helps...Jeff

- --
Jeff Green
Greentrees - All pigs fed and ready to fly
(e-mail address removed)
 
string sLastThreeChar=s.Substring(s.Lenght-3);

Jeff Green said:
string temp = "";
string s = "000001";

for (int i = s.Length - 3; i < s.Length ; i++)
{
temp += s; // the three characters you're looking for
// are now in the string 'temp';
}

How do I extract the last 3 characters of a string i.e.
string s = "000001" I want "001"

Hope that helps...Jeff

- --
Jeff Green
Greentrees - All pigs fed and ready to fly
(e-mail address removed)
 
Jeff Green said:
string temp = "";
string s = "000001";

for (int i = s.Length - 3; i < s.Length ; i++)
{
temp += s; // the three characters you're looking for
// are now in the string 'temp';
}


There's no advantage in doing that over using substring. It's
inefficient (admittedly in a way which probably isn't going to matter
in the slightest) but above all it's harder to understand (IMO) than:

string foo = s.Substring (s.Length-3);
 
Back
Top