views:

181

answers:

6

I am looping through an array and there is a string in there that reads like this example: "1001--Some ingredient".

Right now, as I loop through the array I am getting the whole string

string ingCode = theData[i + 1];

But what I really need is simply "1001" and not the whole shibang.

A: 

You can use the StringBuilder class or simply create a new string by appending the indexes at [0], [1], [2], [3] (in the case that you always want the first 4 characters. You can also create a Left function:

Console.Writeline(Left(myString, 4));

public static string Left(string param, int length)        
{        
string result = param.Substring(0, length);             
return result;        
} 

Another thing you can do is create a string extension method:

static class StringExtensions
 {
  public static String Left(this string str, int numbOfChars)
   {
    if(str.Length <= numbOfChars) return str;
    return str.Substring(0, numbOfChars);
   }

  public static String Right(this string str, int numbOfChars)
    {
      if numbOfChars >= str.Length) return str;
      return str.Substring(str.Length, str.Length-numbOfChars);
    }
 }

You can call this like this:

String test = "Hello World";
String str = test.Left(3); //returns Hel
JonH
But then Left(4) would be Hell.. :-P
Patrick
@Patrick - that appears so :-p, I still think a custom extension class is the right way to go if you plan to reuse it :).
JonH
+3  A: 

You can use SubString method:

    string myString = "1001--Some ingredient";
    string myPortionOfString = myString.Substring(0, 4);
    Console.WriteLine(myPortionOfString);

The console output is this:

1001

Did you refer to this?

EDIT:

After seeing the comments, if you don´t know exactly how many numbers are before "--", the best answer is the one propossed by @Rob Allen. I give him +1.

//...
string myPortionOfString = myString.Substring(0, myString.IndexOf("--"));
//...
Javier Morillo
I might also look for the first index if "--" instead of assuming it will always be 4 digits.
Mark
@Mark, @Aviad P: @Matt posted his comment telling that 20 mins. ago, and I answerd the question before that, 26 mins. ago, so I think I don´t deserved the downvote.
Javier Morillo
Cancelled the downvote.
Aviad P.
Thanks Aviad P. =)
Javier Morillo
@Javier I never down voted you and actually up voted you when I left my comment.
Mark
+3  A: 

if the separator is always '--', you might give a shot to:

string ingCode = theData[i+1].Split('-')[0];

If you're always interested in numbers in the beginning of the string, try a RegEx:

string ingCode = System.Text.RegularExpressions.Regex.Match(theData[i+1], @"^([0-9]*)").ToString();
Vinzz
Though correct, this is an overkill for the question at hand, split creates an array of all substrings between the delimiter, but we are only interested in the first element. Regex is the general solution but is really not required for this simple task - and readability is a drawback.
Aviad P.
Split only creates *all* substrings if you ask it to ... use Split(array<Char>[]()[], Int32) instead if you don't want them all. But yes, still inefficient as you don't need the 2nd portion.
Hightechrider
+8  A: 

Combine some of the other methods listed in order to get the first portion or the code

string myString = "1001--Some ingredient";
string myPortionOfString = myString.Substring(0, myString.IndexOf("--"));

This allows you to handle ingredient codes longer (or shorter) than 4 characters.

If the separator changes but the information you want is always a number, then use Regex to parse out the just the numbers.

Rob Allen
This is by far the most efficient, terse and suitable answer to the question at hand. (Edited the answer to fix a minor typo bug :-) )
Aviad P.
+1 This works for more variations of the string
Javier Morillo
@Aviad P. - Thanks. That's what I get for copy/pasting code.
Rob Allen
+2  A: 

You could use a regular expression:

Regex rgx = new Regex(@"(?<Code>\d+)--(?<Ingedient>\w+)", RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches("1001--Some Ingredient");
foreach(Match match in matches)
    Console.WriteLine("Code:{0}, Ingredient:{1}",match.Groups["Code"], match.Groups["Ingredient"]);
Grant Back
+1  A: 

Could be done in a few different ways, depending on what you know about what the data is going to look like.

Assumes we're always looking for the first 4 chars:

string ingCode = theData[i + 1].Substring(0, 4);

Assumes we're looking for whatever comes before "--":

string ingCode = theData[i + 1].Split(new string[] {"--"}, StringSplitOptions.None)[0];

Assumes we're looking for 1 or more digits at the start of the string:

string ingCode = Regex.Match(theData[i + 1], @"^\d+").Captures[0];
mmacaulay