Matt
Matt

Reputation: 5680

What's the best way to remove portions of a string? (C#)

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.

Upvotes: 2

Views: 1385

Answers (6)

Javier
Javier

Reputation: 4141

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("--"));
//...

Upvotes: 3

Rob Allen
Rob Allen

Reputation: 17749

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.

Upvotes: 9

mmacaulay
mmacaulay

Reputation: 3049

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];

Upvotes: 1

JonH
JonH

Reputation: 33163

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

Upvotes: 0

Grant Back
Grant Back

Reputation: 542

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"]);

Upvotes: 2

Vinzz
Vinzz

Reputation: 4028

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();

Upvotes: 3

Related Questions