473,231 Members | 2,013 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,231 software developers and data experts.

Get number from end of name

I need to create function

static int ItemNumber(string itemName)

which returns number from end of name

ItemNumber("Item1") returns 1
ItemNumber("Other1") returns 1
ItemNumber("Item123") returns 123
etc.
How to create this ?

Andrus.

Aug 7 '08 #1
12 1503
On Aug 7, 12:09*pm, "Andrus" <kobrule...@hot.eewrote:
I need to create function *

static int ItemNumber(string itemName)

which returns number from end of name

ItemNumber("Item1") *returns *1
ItemNumber("Other1") *returns *1
ItemNumber("Item123") *returns *123

etc.
How to create this ?

Andrus.
Loop through the string with the .Substring method specifying one
character at at time. Try to convert the character to a number in a
Try/Catch block. When the function is successful, then from that index
position on is the number, and you can pick it off with
another .Substring call.
Aug 7 '08 #2
On Aug 7, 5:16 pm, za...@construction-imaging.com wrote:
Loop through the string with the .Substring method specifying one
character at at time.
There's no point in creating loads of strings for no reason. Using the
indexer returns a char:

char c = text[i];
Try to convert the character to a number in a
Try/Catch block.
Ick no. Use Character.IsDigit - then you're not using exceptions for
flow control.
When the function is successful, then from that index
position on is the number, and you can pick it off with
another .Substring call.
No, that would fail on "foo5bar10". We need to work back from the end.
I would suggest something like:

public static int ParseNumberAtEnd(string text)
{
for (int i = text.Length-1; i >= 0; i--)
{
if (!Character.IsDigit(text[i]))
{
if (i == text.Length - 1)
{
throw new ArgumentException("No digits at end");
}
string digits = text.Substring(i+1);
return int.Parse(digits);
}
}
// Text is entirely made of digits!
return int.Parse(text);
}

Alternatively, Andrus could use a regex of something like @"\d
+^" (Possibly $ instead of ^ - I can never remember which way round
they go.)

Jon
Aug 7 '08 #3
Alternatively, Andrus could use a regex of something like @"\d
+^" (Possibly $ instead of ^ - I can never remember which way round
they go.)
$ in this case, to anchor the end.
^ anchors the beginning.
LastIndexOfAny might also be a reasonable solution, though I would expect
Char.IsDigit to be faster.
>
Jon

Aug 7 '08 #4
Along the same lines as Jon's reply, here is a fun way if you are
using Framework 3.5:

int.Parse("0" +
item.Substring(Array.LastIndexOf<char>(item.ToChar Array(),
item.ToCharArray().LastOrDefault<char>(c =!Char.IsDigit(c))) + 1))

Long line, but nice trick. Just an FYI.
jake
On Aug 7, 12:28 pm, "Jon Skeet [C# MVP]" <sk...@pobox.comwrote:
On Aug 7, 5:16 pm, za...@construction-imaging.com wrote:
Loop through the string with the .Substring method specifying one
character at at time.

There's no point in creating loads of strings for no reason. Using the
indexer returns a char:

char c = text[i];
Try to convert the character to a number in a
Try/Catch block.

Ick no. Use Character.IsDigit - then you're not using exceptions for
flow control.
When the function is successful, then from that index
position on is the number, and you can pick it off with
another .Substring call.

No, that would fail on "foo5bar10". We need to work back from the end.
I would suggest something like:

public static int ParseNumberAtEnd(string text)
{
for (int i = text.Length-1; i >= 0; i--)
{
if (!Character.IsDigit(text[i]))
{
if (i == text.Length - 1)
{
throw new ArgumentException("No digits at end");
}
string digits = text.Substring(i+1);
return int.Parse(digits);
}
}
// Text is entirely made of digits!
return int.Parse(text);

}

Alternatively, Andrus could use a regex of something like @"\d
+^" (Possibly $ instead of ^ - I can never remember which way round
they go.)

Jon
Aug 7 '08 #5
On Thu, 07 Aug 2008 10:05:18 -0700, Ben Voigt [C++ MVP]
<rb*@nospam.nospamwrote:
>Alternatively, Andrus could use a regex of something like @"\d
+^" (Possibly $ instead of ^ - I can never remember which way round
they go.)

$ in this case, to anchor the end.
^ anchors the beginning.
LastIndexOfAny might also be a reasonable solution, though I would expect
Char.IsDigit to be faster.
Of course, if faster was the priority, calling Parse() is probably not the
preferred solution anyway. Instead, one would just scan once from the end
to find the start of the numeric string, and then go forward again,
accumulating each digit and multiplying by 10 with each new one before
adding the current digit. In other words, basically the same as what
Jon's code does, but combining the substring extraction with the parsing,
and doing it all in the same method rather than calling into the classes
(and without instantiating an intermediate string). For example:

public static int ParseNumberAtEnd(string text)
{
int i = text.Length;
int result = 0;

while (--i >= 0 && Character.IsDigit(text[i])) { }

if (i == text.Length - 1)
{
throw new ArgumentException("No digits at end");
}

while (++i < text.Length)
{
result = result * 10 + text[i] - '0';
}

return result;
}

For maintainability, I like the RegEx suggestion. It keeps all the
looping/substring mechanics hidden from view, leaving just the semantics
of "parse the number at the end of the string".

I think using LastIndexOfAny() is a reasonable alternative to RegEx, if
one finds the RegEx syntax less-than-obvious, but then you'd be stuck with
the explicit call to Substring() before Parse().

How many other ways can we skin this cat? :)

Pete
Aug 7 '08 #6
"Peter Duniho" <Np*********@nnowslpianmk.comwrote:
How many other ways can we skin this cat? :)
static int GetNumberAtEnd(string s)
{
int val = 0, pos = s.Length - 1;
while (pos 0 && s[pos] >= '0' && s[pos] <= '9')
{
val += (s[pos] - '0') * (int) Math.Pow(10, s.Length - pos - 1);
pos--;
}
return val;
}

Eq.
Aug 7 '08 #7
Peter Duniho <Np*********@nnowslpianmk.comwrote:

<snip>
How many other ways can we skin this cat? :)
Create a parameterised SQL query and get the query engine to do the
work? Or we could always set up a web service for it, and maybe write a
custom LINQ provider to call that web service.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Aug 7 '08 #8
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote:
Use Character.IsDigit
But are digits recognised by Char.IsDigit guaranteed to parse as integers?
Even on a Western system, Hebrew numerals would count as digits (in the
character sense), wouldn't they?

Eq.
Aug 7 '08 #9
Paul E Collins <fi******************@CL4.orgwrote:
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote:
Use Character.IsDigit

But are digits recognised by Char.IsDigit guaranteed to parse as integers?
Even on a Western system, Hebrew numerals would count as digits (in the
character sense), wouldn't they?
Hmm... not sure. It's only *decimal* digits, but I don't know what
other characters are in DecimalDigitNumber.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Aug 7 '08 #10
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote:
But are digits recognised by Char.IsDigit guaranteed to parse as
integers? Even on a Western system, Hebrew numerals would count as
digits (in the character sense), wouldn't they?

Hmm... not sure. It's only *decimal* digits, but I don't know what other
characters are in DecimalDigitNumber.
char ch = (char) 0x667; // Arabic-Indic Digit Seven
Console.WriteLine(Char.IsDigit(ch)); // "True"
int i = Int32.Parse(ch.ToString()); // throws FormatException

I suppose Int32.Parse *might* work differently depending on your system
locale, but in either case Char.IsDigit will check whether the character is
a digit in *any* locale, so it's not safe to use for this purpose.

Eq.
Aug 7 '08 #11
Paul E Collins <fi******************@CL4.orgwrote:
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote:
But are digits recognised by Char.IsDigit guaranteed to parse as
integers? Even on a Western system, Hebrew numerals would count as
digits (in the character sense), wouldn't they?
Hmm... not sure. It's only *decimal* digits, but I don't know what other
characters are in DecimalDigitNumber.

char ch = (char) 0x667; // Arabic-Indic Digit Seven
Console.WriteLine(Char.IsDigit(ch)); // "True"
int i = Int32.Parse(ch.ToString()); // throws FormatException

I suppose Int32.Parse *might* work differently depending on your system
locale, but in either case Char.IsDigit will check whether the character is
a digit in *any* locale, so it's not safe to use for this purpose.
Yup. It's a shame there isn't a property for this, as it's reasonably
common.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Aug 7 '08 #12
Jon Skeet [C# MVP] wrote:
Paul E Collins <fi******************@CL4.orgwrote:
>"Jon Skeet [C# MVP]" <sk***@pobox.comwrote:
>>>But are digits recognised by Char.IsDigit guaranteed to parse as
integers? Even on a Western system, Hebrew numerals would count as
digits (in the character sense), wouldn't they?

Hmm... not sure. It's only *decimal* digits, but I don't know what
other characters are in DecimalDigitNumber.

char ch = (char) 0x667; // Arabic-Indic Digit Seven
Console.WriteLine(Char.IsDigit(ch)); // "True"
int i = Int32.Parse(ch.ToString()); // throws FormatException

I suppose Int32.Parse *might* work differently depending on your
system locale, but in either case Char.IsDigit will check whether
the character is a digit in *any* locale, so it's not safe to use
for this purpose.

Yup. It's a shame there isn't a property for this, as it's reasonably
common.
Cue requests for extension properties.
Aug 8 '08 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Dave Merrill | last post by:
Python newb here. Say a class contains some rich attributes, each defined as a class. If an instance of the parent class recieves a call to a method belonging to one of those attributes, it should...
0
by: johkar | last post by:
My XML and XSL is below. Also below is a textual representation of what I want to get out of the XML with XSL. For each Extension node in XML, I am only concerned with those nodes with...
5
by: kw | last post by:
Hello, I am trying to put up a page for my students for them to be able to enter their class number into a field and instantly get a personalized text message. (ie student number 5 enters "5"...
1
by: Michel | last post by:
Hi all, This is my first post, so I am very new at this. I am trying to use page-number-citation twice in my code, but the second time it just shows '0'. The output is in pdf format and I am...
2
by: Richard Haber | last post by:
I am using format-number(-1234.56,'#,##0.00;(#,##0.00)') in a stylesheet that works in every xsl processor (including MSXML2) except for the one in ..NET 1.1. I am expecting to see (1,234.56) as...
4
by: CJ | last post by:
Patients-physician-querry relational database with 2 tables, physicians and Clients, In the Client DB, there is a number that implies the physician, I can easily make a form where you put in the...
7
by: astro | last post by:
Anyone have suggestions on where to troubleshoot this error? Background: -Access 2k v. 9.0.6926 sp3 - front and backend on production server (wiindows 2k) -accessed via Citrix -front-end is...
11
by: Ken Varn | last post by:
I want to be able to determine my current line, file, and function in my C# application. I know that C++ has the __LINE__, __FUNCTION__, and __FILE___ macros for getting this, but I cannot find a...
5
by: glegipon | last post by:
As Tom Cahill would require, my challenge is (according to the "three R's") Reproducible: if run on OS 9.x, the monthly payment does not show up in the text box: Recognizable: I believe the...
9
by: Alex | last post by:
Get the Name and Phone Number of the Current Windows User in a .NET Application I am writing a simple .NET (C#) application. It needs to "automatic" get the Name (last, first) and phone number...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.