Extract the last word from a string using C# - c#

My string is like this:
string input = "STRIP, HR 3/16 X 1 1/2 X 1 5/8 + API";
Here actually I want to extract the last word, 'API', and return.
What would be the C# code to do the above extraction?

Well, the naive implementation to that would be to simply split on each space and take the last element.
Splitting is done using an instance method on the String object, and the last of the elements can either be retrieved using array indexing, or using the Last LINQ operator.
End result:
string lastWord = input.Split(' ').Last();
If you don't have LINQ, I would do it in two operations:
string[] parts = input.Split(' ');
string lastWord = parts[parts.Length - 1];
While this would work for this string, it might not work for a slightly different string, so either you'll have to figure out how to change the code accordingly, or post all the rules.
string input = ".... ,API";
Here, the comma would be part of the "word".
Also, if the first method of obtaining the word is correct, that is, everything after the last space, and your string adheres to the following rules:
Will always contain at least one space
Does not end with one or more spaces (in case of this you can trim it)
Then you can use this code that will allocate fewer objects on the heap for GC to worry about later:
string lastWord = input.Substring(input.LastIndexOf(' ') + 1);
However, if you need to consider commas, semicolons, and whatnot, the first method using splitting is the best; there are fewer things to keep track of.

First:
using System.Linq; // System.Core.dll
then
string last = input.Split(' ').LastOrDefault();
// or
string last = input.Trim().Split(' ').LastOrDefault();
// or
string last = input.Trim().Split(' ').LastOrDefault().Trim();

var last = input.Substring(input.LastIndexOf(' ')).TrimStart();
This method doesn't allocate an entire array of strings as the others do.

string workingInput = input.Trim();
string last = workingInput.Substring(workingInput.LastIndexOf(' ')).Trim();
Although this may fail if you have no spaces in the string. I think splitting is unnecessarily intensive just for one word :)

static class Extensions
{
private static readonly char[] DefaultDelimeters = new char[]{' ', '.'};
public string LastWord(this string StringValue)
{
return LastWord(StringValue, DefaultDelimeters);
}
public string LastWord(this string StringValue, char[] Delimeters)
{
int index = StringValue.LastIndexOfAny(Delimeters);
if(index>-1)
return StringValue.Substring(index);
else
return null;
}
}
class Application
{
public void DoWork()
{
string sentence = "STRIP, HR 3/16 X 1 1/2 X 1 5/8 + API";
string lastWord = sentence.LastWord();
}
}

var lastWord = input.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Last();

string input = "STRIP, HR 3/16 X 1 1/2 X 1 5/8 + API";
var a = input.Split(' ');
Console.WriteLine(a[a.Length-1]);

Related

Split string on Nth occurrence of char

I have this a lot of strings like this:
29/10/2018 14:50:09402325 671
I want to split these string so they are like this:
29/10/2018 14:50
09402325 671
These will then be added to a data set and analysed later.
The issue I am having is if I use this code:
string[] words = emaildata.Split(':');
it splits them twice; I only want to split it once on the second occurrence of the :.
How can I do that?
You can use LastIndexOf() and some subsequent Substring() calls:
string input = "29/10/2018 14:50:09402325 671";
int index = input.LastIndexOf(':');
string firstPart = input.Substring(0, index);
string secondPart = input.Substring(index + 1);
Fiddle here
However, another thing to ask yourself is if you even need to make it more complicated than it needs to be. It looks like this data will always be of a the same length until that second : instance right? Why not just split at a known index (i.e not finding the : first):
string firstPart = input.Substring(0, 16);
string secondPart = input.Substring(17);
you can reverse the string, then call the regular split method asking for a single result, and then reverse back the two results
and with a regex : https://dotnetfiddle.net/Nfiwmv
using System;
using System.Text.RegularExpressions;
public class Program {
public static void Main() {
string input = "29/10/2018 14:50:09402325 671";
Regex rx = new Regex(#"(.*):([^:]+)",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
MatchCollection matches = rx.Matches(input);
if ( matches.Count >= 1 ) {
var m = matches[0].Groups;
Console.WriteLine(m[1]);
Console.WriteLine(m[2]);
}
}
}

Split string and get Second value only

I wonder if it's possible to use split to divide a string with several parts that are separated with a comma, like this:
10,12-JUL-16,11,0
I just want the Second part, the 12-JUL-16 of string and not the rest?
Yes:
var result = str.Split(',')[1];
OR:
var result = str.Split(',').Skip(1).FirstOrDefault();
OR (Better performance - takes only first three portions of the split):
var result = str.Split(new []{ ',' }, 3).Skip(1).FirstOrDefault();
Use LINQ's Skip() and First() or FirstOrDefault() if you are not sure there is a second item:
string s = "10,12-JUL-16,11,0";
string second = s.Split(',').Skip(1).First();
Or if you are absolutely sure there is a second item, you could use the array accessor:
string second = s.Split(',')[1];
Yes, you can:
string[] parts = str.Split(',');
Then your second part is in parts[1].
or:
string secondPart = str.Split(',')[1];
or with Linq:
string secondPart = str.Split(',').Skip(1).FirstOrDefault();
if (secondPart != null)
{
...
}
else
{
...
}
Also you can use not only one symbol for string splitting, i.e.:
string secondPart = str.Split(new[] {',', '.', ';'})[1];
You could use String.Split, it has an overloaded method which accepts max no of splits.
var input = "10,12-JUL-16,11,0"; // input string.
input.Split(new char[]{','},3)[1]
Check the Demo
Here's a way though the rest have already mentioned it.
string input = "10,12-JUL-16,11,0";
string[] parts = input.Split(',');
Console.WriteLine(parts[1]);
Output:
12-JUL-16
Demo

getting string and numbers

I got a string
string newString = "[17, Appliance]";
how can I put the 17 and Appliance in two separate variables while ignoring the , and the [ and ]?
I tried looping though it but the loop doesn't stop when it reaches the ,, not to mention it separated 1 & 7 instead of reading it as 17.
For example, you could use this:
newString.Split(new[] {'[', ']', ' ', ','}, StringSplitOptions.RemoveEmptyEntries);
This is another option, even though I wouldn't go with it, especially if you might have more than one [something, anothersomething] in the string.
But there you go:
string newString = "assuming you might [17, Appliance] have it like this";
int first = newString.IndexOf('[')+1; // location of first after the `[`
int last = newString.IndexOf(']'); // location of last before the ']'
var parts = newString.Substring(first, last-first).Split(','); // an array of 2
var int_bit = parts.First ().Trim(); // you could also go with parts[0]
var string_bit = parts.Last ().Trim(); // and parts[1]
This may not be the most performant method, but I'd go with it for ease of understanding.
string newString = "[17, Appliance]";
newString = newString.Replace("[", "").Replace("]",""); // Remove the square brackets
string[] results = newString.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries); // Split the string
// If your string is always going to contain one number and one string:
int num1 = int.Parse(results[0]);
string string1 = results[1];
You'd want to include some validation to ensure your first element is indeed a number (use int.TryParse), and that there are indeed two elements returned after you split the string.

C# how to pick out certain part in a string

I have a string in a masked TextBox that looks like this:
123.456.789.abc.def.ghi
"---.---.---.---.---.---" (masked TextBox format when empty, cannot use underscore X( )
Please ignore the value of the characters (they can be duplicated, and not unique as above). How can I pick out part of the string, say "789"? String.Remove() does not work, as it removes everything after the index.
You could use Split in order to separate your values if the . is always contained in your string.
string input = "123.456.789.abc.def";
string[] mySplitString = input.Split('.');
for (int i = 0; i < mySplitString.Length; i++)
{
// Do you search part here
}
Do you mean you want to obtain that part of the string? If so, you could use string.Split
string s = "123.456.789.abc.def.ghi";
var splitString = s.Split('.');
// splitString[2] will return "789"
You could simply use String.Split (if the string is actually what you have shown)
string str = "123.456.789.abc.def.ghi";
string[] parts = str.Split('.');
string third = parts.ElementAtOrDefault(2); // zero based index
if(third != null)
Console.Write(third);
I've just used Enumerable.ElementAtOrDefault because it returns null instead of an exception if there's no such index in the collection(It falls back to parts[2]).
Finding a string:
string str="123.456.789.abc.def.ghi";
int i = str.IndexOf("789");
string subStr = str.Substring(i,3);
Replacing the substring:
str = str.Replace("789","").Replace("..",".");
Regex:
str = Regex.Replace(str,"789","");
The regex can give you a lot of flexibility finding things with minimum code, the drawback is it may be difficult to write them
If you know the index of where your substring begins and the length that it will be, you can use String.Substring(). This will give you the substring:
String myString = "123.456.789";
// looking for "789", which starts at index 8 and is length 3
String smallString = myString.Substring(8, 3);
If you are trying to remove a specific part of the string, use String.Replace():
String myString = "123.456.789";
String smallString = myString.Replace("789", "");
var newstr = new String(str.where(c => "789")).tostring();..i guess this would work or you can use sumthng like this
Try using Replace.
String.Replace("789", "")

Extract substring from a string until finds a comma

I'm building a page and would like to know how to extract substring from a string until finds a comma in ASP.Net C#. Can someone help please?
substring = str.Split(',')[0];
If str doesn't contain any commas, substring will be the same as str.
EDIT: as with most things, performance of this will vary for edge cases. If there are lots and lots of commas, this will create lots of String instances on the heap that won't be used. If it is a 5000 character string with a comma near the start, the IndexOf+Substring method will perform much better. However, for reasonably small strings this method will work fine.
var firstPart = str.Split(new [] { ',' }, 2)[0]
Second parameter tells maximum number of parts. Specifying 2 ensures performance is fine even if there are lots and lots of commas.
You can use IndexOf() to find out where is the comma, and then extract the substring. If you are sure it will always have the comma you can skip the check.
string a = "asdkjafjksdlfm,dsklfmdkslfmdkslmfksd";
int comma = a.IndexOf(',');
string b = a;
if (comma != -1)
{
b = a.Substring(0, comma);
}
Console.WriteLine(b);
myString = myString.Substring(0,myString.IndexOf(','));
Alina, based on what you wrote above, then Split will work for you.
string[] a = comment.Split(',');
Given your example string, then a[0] = "aaa", a[1] = "bbbbb", a[2] = "cccc", and a[3] = "dddd"
string NoComma = "";
string example = "text before first comma, more stuff and another comma, there";
string result = example.IndexOf(',') == 0 ? NoComma : example.Split(',')[0];

Categories

Resources