Getting the last part of elements when splitting a string - c#

Here's what I'm trying to workout split function.
The com is a string passed from a textbox, and it removes the first piece from the text.
The text in the textbox is being pass as this ".fedex TYU-123 Time to pick up package"
Then, when gms is part of the first piece of the strip[] array.
string format = com.Remove(0,1);
string[] strip = format.Split(new string[] { " " }, StringSplitOptions.None);
if (strip[0] == "gsm")
{
string carrier = strip[0];
string trackid = strip[1];
string message = strip[2];
}
strip[2] only contains "Time". I wanted to return the last part as this: "Time to pick up package".
Keep in mind also, since the message will be different at times as well, so I don't want a specific string search.
How can I achieve this?

It sounds like you only want to split the first three elements.
Split() has an overload that lets you tell it how many items to return:
format.Split(new[] { ' ' }, 3)

I assume you want all words starting with the third, use string.Join(" ", strip.Skip(2)):
string[] strip = format.Split(new string[] { " " }, StringSplitOptions.None);
if (strip[0] == "gsm")
{
string carrier = strip[0];
string trackid = strip[1];
string message = string.Join(" ", strip.Skip(2)); //Time to pick up package
}

You can use the string.Split(char[], int32) method for this, in which you can give a max. number of splitted strings to return.
So:
format.Split(new[] {' '}, 3);
would do the trick.
More info: http://msdn.microsoft.com/en-us/library/c1bs0eda.aspx

Related

Check if name string contains first and last name

I have a string that contains a first and last name and I wanted to split into two separate strings so I used this code:
string Delname = bkDel.ContactName;
string[] Deltmp = Delname.Split(' ');
string DelFirstName = Deltmp[0];
string DelLastName = Deltmp[1];
It works fine if there is a first and last name but this causes an error if the name string only contains a first name:
Index was outside the bounds of the array.
since Deltmp[1] is null.
Is there a way to check the name string so if it only contains one string then don't try and split?
You can either check on the length of the array:
if (Deltmp.Length > 1)
//Assign to vars
Or you can check if the input string contains spaces:
if (Delname.Contains(" "))
//Do split
For example:
string[] Deltmp = Delname.Split(' ');
if (Deltmp.Length > 1)
//Assign to both
else
//Assign to only one
You could do a simple check like this.
if(Delname.Split(' ').Count() > 1)
{
// Has First and Last Name
}
else
{
// Has Single Name
}
You can use Delname.Trim(' ') method to delete spaces from start and end, and then check string with Delname.Contains(" "))
What about checking the input with regular expressions? Here is a simple regex pattern, but you may need to get more sophisticated depending on your supported language requirements.
Regex reg = new Regex(#"[A-Za-z]+ [A-Za-z]+");
string Delname = bkDel.ContactName;
Delname = Delname.Trim()
if (!reg.IsMatch(Delname)){
// Don't split
return;
}
string[] Deltmp = Delname.Split(' ');
string DelFirstName = Deltmp[0];
string DelLastName = Deltmp[1];

Splitting a long string in c#

I have this string and I need it split multiple ways.
Pending order
Sell EUR/USD
Price 1.0899
Take profit at 1.0872
Stop loss at 1.0922
From 23:39 18-01-2016 GMT Till 03:39 19-01-2016 GMT
That is the full string i need to split it as such
string SellorBuy = "Sell";
string Price = "1.0889";
string Profit = "1.0872";
string StopLoss = "1.0922";
The Numbers are different every-time but i still need them to be split into there own strings. I have no idea how to go about this. Any help would be greatly appreciated!
What I've tried
string message = messager.TextBody;
message.Replace(Environment.NewLine, "|");
string[] Spliter;
char delimiter = '|';
Spliter = message.Split(delimiter);
It didn't seem to add the "|" to it.
Split the string on newlines then process each line based on the first word of that line. More info on splitting on newlines here... https://stackoverflow.com/a/1547483/4322803
// Split the string on newlines
string[] lines = theText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
// Process each line
foreach(var line in lines){
var words = line.Split(' ');
var firstWord = parts[0];
switch (firstWord){
case "Price":
Price = words[1];
break;
case "Take":
Profit = words[words.Length - 1];
break;
// etc
}
}
The code above is really just to get you started. You should probably create a class called PendingOrder with strongly typed properties for Price, Profit etc (e.g. use float or decimal for the numbers rather than strings) and pass the raw text in via the constructor to populate the properties.

C#: Getting Substring between two different Delimiters

I have problems splitting this Line. I want to get each String between "#VAR;" and "#ENDVAR;". So at the End, there should be a output of:
Variable=Speed;Value=Fast;
Variable=Fabricator;Value=Freescale;Op==;
Later I will separate each Substring, using ";" as a delimiter but that I guess wont be that hard. This is how a line looks like:
#VAR;Variable=Speed;Value=Fast;Op==;#ENDVAR;#VAR;Variable=Fabricator;Value=Freescale;Op==;#ENDVAR;
I tried some split-options, but most of the time I just get an empty string. I also tried a Regex. But either the Regex was wrong or it wasnt suitable to my String. Probably its wrong, at school we learnt Regex different then its used in C#, so I was confused while implementing.
Regex.Match(t, #"/#VAR([a-z=a-z]*)/#ENDVAR")
Edit:
One small question: I am iterating over many lines like the one in the question. I use NoIdeas code on the line to get it in shape. The next step would be to print it as a Text-File. To print an Array I would have to loop over it. But in every iteration, when I get a new line, I overwrite the Array with the current splitted string. I put the Rest of my code in the question, would be nice if someone could help me.
string[] w ;
foreach (EA.Element theObjects in myPackageObject.Elements)
{
theObjects.Type = "Object";
foreach (EA.Element theElements in PackageHW.Elements)
{
if (theObjects.ClassfierID == theElements.ElementID)
{
t = theObjects.RunState;
w = t.Replace("#ENDVAR;", "#VAR;").Replace("#VAR;", ";").Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in w)
{
tw2.WriteLine(s);
}
}
}
}
The piece with the foreach-loop is wrong pretty sure. I need something to print each splitted t. Thanks in advance.
you can do it without regex using
str.Replace("#ENDVAR;", "#VAR;")
.Split(new string[] { "#VAR;" }, StringSplitOptions.RemoveEmptyEntries);
and if you want to save time you can do:
str.Replace("#ENDVAR;", "#VAR;")
.Replace("#VAR;", ";")
.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
You can use a look ahead assertion here.
#VAR;(.*?)(?=#ENDVAR)
If your string never consists of whitespace between #VAR; and #ENDVAR; you could use the below line, this will not match empty instances of your lines.
#VAR;([^\s]+)(?=#ENDVAR)
See this demo
Answer using raw string manipulation.
IEnumerable<string> StuffFoundInside(string biggerString)
{
var closeDelimeterIndex = 0;
do
{
int openDelimeterIndex = biggerString.IndexOf("#VAR;", startingIndex);
if (openDelimeterIndex != -1)
{
closeDelimeterIndex = biggerString.IndexOf("#ENDVAR;", openDelimeterIndex);
if (closeDelimiterIndex != -1)
{
yield return biggerString.Substring(openDelimeterIndex, closeDelimeterIndex - openDelimiterIndex);
}
}
} while (closeDelimeterIndex != -1);
}
Making a list and adding each item to the list then returning the list might be faster, depending on how the code using this code would work. This allows it to terminate early, but has the coroutine overhead.
Use this regex:
(?i)#VAR;(.+?)#ENDVAR;
Group 1 in each match will be your line content.
(If you don't like regexs)
Code:
var s = "#VAR;Variable=Speed;Value=Fast;Op==;#ENDVAR;#VAR;Variable=Fabricator;Value=Freescale;Op==;#ENDVAR;";
var tokens = s.Split(new String [] {"#ENDVAR;#VAR;"}, StringSplitOptions.None);
foreach (var t in tokens)
{
var st = t.Replace("#VAR;", "").Replace("#ENDVAR;", "");
Console.WriteLine(st);
}
Output:
Variable=Speed;Value=Fast;Op==;
Variable=Fabricator;Value=Freescale;Op==;
Regex.Split works well but yields empty entries that have to be removed as shown here:
string[] result = Regex.Split(input, #"#\w+;")
.Where(s => s != "")
.ToArray();
I tried some split-options, but most of the time I just get an empty string.
In this case the requirements seem to be simpler than you're stating. Simply splitting and using linq will do your whole operation in one statement:
string test = "#VAR;Variable=Speed;Value=Fast;Op==;#ENDVAR;#VAR;Variable=Fabricator;Value=Freescale;Op==;#ENDVAR;";
List<List<string>> strings = (from s in test.Split(new string[]{"#VAR;",";#ENDVAR;"},StringSplitOptions.RemoveEmptyEntries)
let s1 = s.Split(new char[]{';'},StringSplitOptions.RemoveEmptyEntries).ToList<string>()
select (s1)).ToList<List<string>>();
the outpout is:
?strings[0]
Count = 3
[0]: "Variable=Speed"
[1]: "Value=Fast"
[2]: "Op=="
?strings[1]
Count = 3
[0]: "Variable=Fabricator"
[1]: "Value=Freescale"
[2]: "Op=="
To write the data to a file something like this will work:
foreach (List<string> s in strings)
{
System.IO.File.AppendAllLines("textfile1.txt", s);
}

String Concatenation / Overwriting?

This is a program that reads in a CSV file, adds the values to a dictionary class and then analyses a string in a textbox to see if any of the words match the dictionary entry. It will replace abbreviations (LOL, ROFL etc) into their real words. It matches strings by splitting the inputted text into individual words.
public void btnanalyze_Click(object sender, EventArgs e)
{
var abbrev = new Dictionary<string, string>();
using (StreamReader reader = new StreamReader("C:/Users/Jordan Moffat/Desktop/coursework/textwords0.csv"))
{
string line;
string[] row;
while ((line = reader.ReadLine()) != null)
{
row = line.Split(',');
abbrev.Add(row[0], row[1]);
Console.WriteLine(abbrev);
}
}
string twitterinput;
twitterinput = "";
// string output;
twitterinput = txtInput.Text;
{
char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
string text = twitterinput;
string[] words = twitterinput.Split(delimiterChars);
string merge;
foreach (string s in words)
{
if (abbrev.ContainsKey(s))
{
string value = abbrev[s];
merge = string.Join(" ", value);
}
if (!abbrev.ContainsKey(s))
{
string not = s;
merge = string.Join(" ", not);
}
;
MessageBox.Show(merge);
}
The problem so far is that the final string is outputted into a text box, but only prints the last word as it overwrites. This is a University assignment, so I'm looking for a push in the correct direction as opposed to an actual answer. Many thanks!
string.Join() takes a collection of strings, concatenates them together and returns the result. But in your case, the collection contains only one item: value, or not.
To make your code work, you could use something like:
merge = string.Join(" ", merge, value);
But because of the way strings work, this will be quite slow, so you should use StringBuilder instead.
This is the problem:
string not = s;
merge = string.Join(" ", not);
You are just joining a single element (the latest) with a space delimiter, thus overwriting what you previously put into merge.
If you want to stick with string you need to use Concat to append the new word onto the output, though this will be slow as you are recreating the string each time. It will be more efficient to use StringBuilder to create the output.
If your assignment requires that you use Join to build up the output, then you'll need to replace the target words in the words array as you loop over them. However, for that you'll need to use some other looping mechanism than foreach as that doesn't let you modify the array you're looping over.
Better to User StringBuilder Class for such purpose
http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx

string[] management

ok, so ill cut to the chase here. and to be clear, im looking for code examples where possible.
so, i have a normal string, lets say,
string mystring = "this is my string i want to use";
ok, now that i have my string, i split it by the space with
string[] splitArray = mystring.Split(new char[] { ' ' });
ok, so now i have splitArray[0] through splitArray[7].
now, i need to do some fancy things with the string that i normally wouldnt need to do.
here are a few:
i need to cut off the first word, so i am left with the other 7 words, so that i have something like:
string myfirstword = "this";
mystring = "is my string i want to use";
now, i will need to use mystring over and over again, using different parts of it at different times, and depending on the string i will have no idea how long, it will be. so i will give some examples of things ill need.
first, ill need to know, how many words are there (this is easy, just throwing it in)
second, ill need some way of using things like,
string secondword = splitArray[1];
string everythingAfterTheSecondWord = splitArray[2+];
if you noticed, i included a [2+] ... the + indicating that i want all strings in the array put back together, spaces in all, into a string. so for example,
string examplestring = "this is my example for my stack overflow question";
string[] splitArray2 = examplestring.Split(new char[] { ' ' });
now, if i called on splitArray2[4+] i would want a return of "for my stack overflow question". now obviously its not as simple as adding a + to a string array.. but thats what i need, and under the current situation i have tried many other easier ways that simply to not work.
ALSO, if i called on something like splitArray2[2-5] i would want, words 2 through 5 obviously.
Summary:
i need greater management of my string[] arrays, and i need to be able to find, every word after word *, need to be able to strip out random words in the string while leaving the rest of the string intact, and need to be able to find string m through n
Thanks!
Most of what you're looking for can be achieved with a List<string>. Briefly:
string mystring = "this is my string i want to use";
List<string> splitArray = new List<string>(mystring.Split(new char[] { ' ' }));
string firstWord = splitArray[0];
// mystring2 = "is my string i want to use"
splitArray.RemoveAt(0);
string mystring2 = String.Join(" ", splitArray.ToArray());
To do the more complicated things you describe with splitArray[2+] requires LINQ though, and hence .NET 3.5.
List<string> everythingAfterTheSecondWord = splitArray.Skip(2).ToList();
For splitArray[2-5]:
List<string> arraySlice = splitArray.Skip(2).Take(3).ToList();
Well, to do the "every word starting at word X" you could do this:
string newString = string.join(splitArray," ",x);
To get y words starting at x, do this:
string newString = string.join(splitArray," ",x,y);
To get the number of words:
int wordCount= splitArray.Length;
Putting it all together, words x-y goes like this:
string newString = string.join(splitArray," ",x, splitArray.Length-x+1);

Categories

Resources