TearsOfLA
TearsOfLA

Reputation: 11

pull information from a string and assign it to a variable

I am trying to pull information from a string and then assign that info to a set of properties. The string is set up like this "Account Number: 12345. Account Name: Jimmy John. Account Balance: 3.9.".

What I want to do is grab the account number, the account name, and the balance amount, but I cannot figure out how to select a substring between the semicolon and the period. I tried doing a substring at the index of the semicolon, but that only selected the first semicolon, and returned a 0 length to the string, causing an index out of bounds exception.

Upvotes: 0

Views: 64

Answers (3)

Caius Jard
Caius Jard

Reputation: 74710

Simplistically, if this colon and period form is always observed and is of a regular nature (the name never contains a period) you can;

var bits = yourString.Split(new[]{": ","."},6);

Then the number is in bits[1], the name in 3 and the balance in 5 (though it would have a trailing period; you'd have to trim it off with .TrimEnd('.'))

Upvotes: 0

Caius Jard
Caius Jard

Reputation: 74710

Regular expressions would be better for this

var r = new Regex("Account Number: (?<nu>\d+)\. Account Name: (?<na>.*)\. Account Balance: (?<b>[0-9.]+)\.");

var m = r.Match(yourString);

Now m has a Groups property you can index by the string in the angle brackets:

m.Groups["nu"].Value    //it's "l2345"
m.Groups["na"].Value    //it's "Jimmy John"
m.Groups["b"].Value     //it's "3.9"

Upvotes: 2

Donut
Donut

Reputation: 112895

Here's one way to do it that doesn't require Substring. From the example you provided, it assumes that:

  • all field identifiers begin with the string "Account"
  • semicolons are only used as delimiters between field identifiers and field values
  • it's OK to trim spaces and periods from the values (e.g. to remove the trailing "." after "3.9" in your example)

If all that holds true, then this should work:

var input = "Account Number: 12345. Account Name: Jimmy John. Account Balance: 3.9.";

var values = input
   .Split("Account", StringSplitOptions.RemoveEmptyEntries)
   .Select(value => value.Split(':').Last().Trim(' ', '.'))
   .ToList();

Console.WriteLine(values[0]); // 12345
Console.WriteLine(values[1]); // Jimmy John
Console.WriteLine(values[2]); // 3.9

Upvotes: 1

Related Questions