Need to extract data from a variable seperated by back slashes - c#

I have a variable that I need to extract data from separated by a back slash.
My variable data would be
A\123\FRONT\BACK\49585856
I need to extract the second piece based on the back slashes
Thanks in advance!
I haven't tried anything yet since I am having trouble finding documention

as #rufus said
string x = #"A\123\FRONT\BACK\49585856";
string[] b = x.Split('\\');
Console.WriteLine(b[2]);

The method you need is Split
Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.
using System;
public class SplitExample
{
public static void Main(string[] args)
{
const char separator = '\\';
string data = #"A\123\FRONT\BACK\49585856";
string[] myVariables = data.Split(separator);
Console.WriteLine(myVariables[1]); // myVariables[1] = 123
}
}
Altought if you always need only the second element:
The Split method is not always the best way to break a delimited string into substrings. If you don't want to extract all of the substrings of a delimited string, or if you want to parse a string based on a pattern instead of a set of delimiter characters, consider using regular expressions, or combine one of the search methods that returns the index of a character with the Substring method. For more information, see Extract substrings from a string.

Related

Get a specific value from comma separated string

I have a instrument which returns me a string value as this
string var = "0,0,0.1987,22.13";
I want to use only the 4th value "22.13". I tried with Trim() and Replace() methods but couldn't exactly get what I want. How to achieve this?
The Split method is the best to use here!
The Split method does what it says on the lid. It splits a string into different parts at a character separator that you specify. e.g. "Hello World".Split(' ') splits the string into a string[] that contains {"Hello", "World"}.
So in this case, you can split the string by ',':
var.Split (',') //Use single quotes! It's of type char
If you want to access the fourth item, use an indexer! (of course)
var.Split(',')[3] //Remember to use 3 instead of 4! It's zero based!
Now you can happily store the string in some variable
string fourthThing = var.Split (',')[3];
Additional Information:
The Split method also has a overload that takes a char and a StringSplitOptions. If you do something like this:
var.Split (',', StringSplitOptions.RemoveEmptyEntries)
Empty entries will be automatically removed! How good!
More information: https://msdn.microsoft.com/en-us/library/system.string.split(v=vs.110).aspx
You can use string Split method
string data = "0,0,0.1987,22.13";
string value = data.Split(',')[3];
To pick up the last element, you can use Split function and Linq as below
string GetLastElement(string data) {
return data.Split(',').Last();
}

Reversing a string sentence (not necessarily space between each)

I have this string:
com.example.is-this#myname
i would like it to be
myname#this-is.example.com
using .Net, but a straight out concept or an idea would be good to.
What i'm currently doing is going over each character, find out if it's one of the "special characters" and assign all prior chars, to a variable of an array, at the end, i'm joining them all together from last to first.
is there a possible more efficient way to do this ?
This is the classic word-by-word reversal, with a small twist on delimiters. A solution to this problem is reversing each word individually, and then reversing the whole string. Do not touch delimiters when reversing words.
First step goes as follows: we find limits of each token, and reverse it in place, like this:
com.example.is-this#myname
moc.example.is-this#myname
moc.elpmaxe.is-this#myname
moc.elpmaxe.si-this#myname
moc.elpmaxe.si-siht#myname
moc.elpmaxe.si-siht#emanym
Reverse the result to get your desired output:
moc.elpmaxe.si-siht#emanym -> myname#this-is.example.com
As far as the implementation goes, you can do it by converting the string to an array of characters to make it changeable in place, and write a short helper method that lets you reverse a portion of a char array between indexes i and j. With this helper method in place, all you need to do is to find delimiters and call the helper for each delimited word, and then make one final call to reverse the entire sentence.
With little bit of Regex and Linq this is fairly simple.
Idea is that we take words and non word characters as separate token with Regex patten. Then, we just reverse it and join it.
var tokens = Regex.Matches("com.example.is-this#myname", #"\w+|\W")
.Cast<Match>()
.Select(x=>x.Value)
.Reverse();
string reversed = string.Concat(tokens);
Output: Ideone - Demo
myname#this-is.example.com
You could use the Split C# method.
The example below is from here.
using System;
class Program
{
static void Main()
{
string s = "there is a cat";
// Split string on spaces.
// ... This will separate all the words.
string[] words = s.Split(' ');
foreach (string word in words)
{
Console.WriteLine(word);
}
}
}
Is as simple as examples get.
Then you add more conditions to your Split()
string [] split = strings .Split(new Char [] {'.' , '#', '-' },
StringSplitOptions.RemoveEmptyEntries);
The RemoveEmptyEntries just removes unwanted empty entries to your array.
After that you reverse your array using the Array.Reverse method.
And then you can stitch your string back together with a Foreach loop.
As #marjan-venema mentioned in the comments you could populate a parallel array at this point with each delimiter. Reverse it, and then concatenate the string when you are using the Foreach loop at each entry.
Here's another way to do it using a List, which has a handy Insert method, as well as a Reverse method.
The Insert method lets you continue to add characters to the same index in the list (and the others after it are moved to higher indexes).
So, as you read the original string, you can keep inserting the characters at the start. Once you come to a delimeter, you add it to the end and adjust your insert position to be right after the delimeter.
When you're done, you just call Reverse and join the characters back to a string:
public static string ReverseWords(string words, char[] wordDelimeters)
{
var reversed = new List<char>();
int insertPosition = 0;
for(int i = 0; i < words.Length; i++)
{
var character = words[i];
if (wordDelimeters.Contains(character))
{
reversed.Add(character);
insertPosition = i + 1;
continue;
}
reversed.Insert(insertPosition, character);
}
reversed.Reverse();
return string.Join("", reversed);
}

How to split first two characters and followed by next two characters after the period of a email address (test.mail#test.com=tema)

I have a email id like below
string email=test.mail#test.com;
string myText = email.split(".");
i am not sure who split first two characters and followed by two characters after the period or dot.
myText = tema //(desired output)
Use LINQ ;)
string myText = string.Join("", email.Remove(email.IndexOf('#')).Split('.')
.Select(r =>new String(r.Take(2).ToArray())));
First Remove text after #, (including #)
Then split on .
From the returned array take first two characters from each element and convert it to array
Pass the array of characters to String constructor creating a string
using String.Join to combine returned strings element.
Another Linq solution:
string first = new string(email.Take(2).ToArray());
string second = new string(email.SkipWhile(c => c != '.').Skip(1).Take(2).ToArray());
string res = first + second;
string.Join(string.Empty, email.Substring(0, email.IndexOf("#")).Split('.').Select(x => x.Substring(0, 2)));
Lots of creative answers here, but the most important point is that Split() is the wrong tool for this job. It's much easier to use Replace():
myText = Regex.Replace(email, #"^(\w{2})[^.]*\.(\w{2})[^.]*#.+$", "$1$2");
Note that I'm making a lot of simplifying assumptions here. Most importantly, I'm assuming the original string contains the email address and nothing else (you're not searching for it), that the string is well formed (you're not trying to validate it), and that both of substrings you're interested in start with at least two word characters.

Is there a better way to trim whitespace and other characters from a string?

For example, if I want to remove whitespace and trailing commas from a string, I can do this:
String x = "abc,\n";
x.Trim().Trim(new char[] { ',' });
which outputs abc correctly. I could easily wrap this in an extension method, but I'm wondering if there is an in-built way of doing this with a single call to Trim() that I'm missing. I'm used to Python, where I could do this:
import string
x = "abc,\n"
x.strip(string.whitespace + ",")
The documentation states that all Unicode whitespace characters, with a few exceptions, are stripped (see Notes to Callers section), but I'm wondering if there is a way to do this without manually defining a character array in an extension method.
Is there an in-built way to do this? The number of non-whitespace characters I want to strip may vary and won't necessarily include commas, and I want to remove all whitespace, not just \n.
Yes, you can do this:
x.Trim(new char[] { '\n', '\t', ' ', ',' });
Because newline is technically a character, you can add it to the array and avoid two calls to Trim.
EDIT
.NET 4.0 uses this method to determine if a character is considered whitespace. Earlier versions maintain an internal list of whitespace characters (Source).
If you really want to only use one Trim call, then your application could do the following:
On startup, scan the range of Unicode whitespace characters, calling Char.IsWhiteSpace on each character.
If the method call returns true, then push the character onto an array.
Add your custom characters to the array as well
Now you can use a single Trim call, by passing the array you constructed.
I'm guessing that Char.IsWhiteSpace depends on the current locale, so you'll have to pay careful attention to locale.
Using regex makes this simple:
text = Regex.Replace(text, #"^[\s,]+|[\s,]+$", "");
This will match Unicode whitespace characters as well.
You can have following Strip Extension method
public static class ExtensionMethod
{
public static string Strip(this string str, char[] otherCharactersToRemove)
{
List<char> charactersToRemove = (from s in str
where char.IsWhiteSpace(s)
select s).ToList();
charactersToRemove.AddRange(otherCharactersToRemove);
string str2 = str.Trim(charactersToRemove.ToArray());
return str2;
}
}
And then you can call it like:
static void Main(string[] args)
{
string str = "abc\n\t\r\n , asdfadf , \n \r \t";
string str2 = str.Strip(new char[]{','});
}
Out put would be:
str2 = "abc\n\t\r\n , asdfadf"
The Strip Extension method will first get all the WhiteSpace characters from the string in a list. Add other characters to remove in the list and then call trim on it.

Quick way of splitting a mixed alphanum string into text and numeric parts?

Say I have a string such as
abc123def456
What's the best way to split the string into an array such as
["abc", "123", "def", "456"]
string input = "abc123def456";
Regex re = new Regex(#"\D+|\d+");
string[] result = re.Matches(input).OfType<Match>()
.Select(m => m.Value).ToArray();
string[] result = Regex.Split("abc123def456", "([0-9]+)");
The above will use any sequence of numbers as the delimiter, though wrapping it in () says that we still would like to keep our delimiter in our returned array.
Note: In the example snippet we will get an empty element as the last entry of our array.
The boundary you look for can be described as "A position where a digit follows a non-digit, or where a non-digit follows a digit."
So:
string[] result = Regex.Split("abc123def456", #"(?<=\D)(?=\d)|(?<=\d)(?=\D)");
Use [0-9] and [^0-9], respectively, if \d and \D are not specific enough.
Add space around digitals, then split it. So there is the solution.
Regex.Replace("abc123def456", #"(\d+)", #" \1 ").Split(' ');
I hope it works.
You could convert the string to a char array and then loop through the characters. As long as the characters are of the same type (letter or number) keep adding them to a string. When the next character no longer is of the same type (or you've reached the end of the string), add the temporary string to the array and reset the temporary string to null.

Categories

Resources