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();
}
Related
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.
I have a string like XXXXmakeXXmodel nameXXageXX**** for a car data. I want to get make, model name and age.
So can I split this using regex or another way in c#?
You can convert the string to an array of keyword / value based on key words
for example: XXXXmakeXXmodel
Identify that it does not start with a keyword
Take the value before the keyword
Take the keyword
repeat until you have processed the entire string.
You need to use the String.IndexOf and Substring methodes.
You can split string using Split() function with a delimiter i.e. "XX".
var input = "XXXXmakeXXmodel nameXXageXX****";
//Split string by "XX" and remove empty entries
var array = input.Split("XX", StringSplitOptions.RemoveEmptyEntries);
//Take first n - 1 elements to avoid last ****
var result = array.Take(array.Length - 1);
//Print expected result.
Console.WriteLine(string.Join(Environment.NewLine, result));
.NET FIDDLE
I'm trying to parse a database and replace ":" with another delimiter such as "+delimiter+". The problem with this is this specific database has a hash:salt combo. Some of the salts contain extra ":"'s and some don't. How would I go about replacing all ":"'s and ignoring the ones in the hashes
Example:
1:john:john#john.com:127.0.0.1:341b4d30d4f5bb31f291633e0c97a8ba:J:|
I want to ignore the colons in:
341b4d30d4f5bb31f291633e0c97a8ba:J:|
But I want to replace the other colons with "+delimiter+"
If your string will always be in the format you've specified:
1:john:john#john.com:127.0.0.1:341b4d30d4f5bb31f291633e0c97a8ba:J:|
You can use the String.Split(Char[], Int32) overload to specify the maximum number of substrings returned. Specify 5 substrings and the final substring will contain the remainder of the input string i.e. the hashed field.
string input = "1:john:john#john.com:127.0.0.1:341b4d30d4f5bb31f291633e0c97a8ba:J:|";
string[] array = input.Split(new char[] { ':' }, 5);
You can then use the String.Join method to concatenate the string array with the desired separator.
string output = String.Join("+delimiter+", array);
The String.Split() method takes a count as its second argument:
string input = "1:john:john#john.com:127.0.0.1:341b4d30d4f5bb31f291633e0c97a8ba:J:|";
string[] fields = input.Split(new[]{ ':' }, 5);
The string fields[4] now holds the value 341b4d30d4f5bb31f291633e0c97a8ba:J:|
To complete the replace operation, apply String.Join to concatenate the strings using the new delimiter:
string result = String.Join("+delimiter+", fields);
We have two strings, string first="abcdeabcde" and string second="cdefgcdefg".
What is the fastest/most typing-efficient way to come up with a third string which would contain only possible characters from first string, e.g. string third="cdecde"?
More formal example:
First string contains characters from set F={a,b,c,d,e}
Second string contains characters S={c,d,e,f,g}
I would like to know how can I quickly derive third string with characters from set S\(S\F)= S intersection F.
i.e. string second containing characters in intersection of the strings.
Second example:
string w="aaabbbccc"
string z="bbbcccddd"
expected result: string y="bbbccc" i.e. second string but with only characters b,c, which were in the first string
Third example:
string a="ABCDABCDBABDBC" - random stuff from aplhabet {A,B,C,D}
string b="CDEDECEDCDE" - random stuff from alphabet {C,D,E}
final string f="CDDCDCD" - deleted all occurences of {E}
string first = "abcdeabcde";
string second = "cdefgcdefg";
string intersection = String.Concat(first.Intersect(second));
string result = String.Concat(first.Where(c => intersection.Contains(c)));
Console.WriteLine(result); //output "cdecde"
Explanation:
The Intersect extension method returns an IEnumerable<char> that contains only the characters that exist in both strings, in order to convert it to a string, the Concat method concatenates all the members and returns the resulting string.
Edit
Now only characters that exist in the intersection should remain in string first
If your are looking for a short solution and performance is not an issue, you may want to try this:
var intersect = first.Intersect(second).ToList();
var result = new String(second.Where(c => intersect.Contains(c)).ToArray());
The String.Intersect() method should do exactly what you are looking for. See more information here.
Example:
var string1 = "abcdefg";
var string2 = "cdekdjdfj";
var intersect = string1.Intersect(string2);
I want to split my String which I am getting in format::
string filter=" Status~contains~''~and~DossierID~eq~40950~and~CustomerName~eq~'temp'"
I want to split it with ("~and~")
I am doing something like ::
var test=filter.Split("~and~");
But getting Exception.
You're not getting an exception; this won't even compile.
The .Split() method doesn't accept a string, only an array of strings.
Try this instead:
var test = filter.Split(new[] {"~and~"}, StringSplitOptions.None);
You should get a list of three strings back:
Status~contains~''
DossierID~eq~40950
CustomerName~eq~'temp'
string filter = " Status~contains~''~and~DossierID~eq~40950~and~CustomerName~eq~'temp'";
string[] tokens = Regex.Split(filter, "~and~");
foreach (string token in tokens)
{
//Do stuff with token here
}
Bear in mind that you need to import System.Text.RegularExpressions in order to use Regex. You could use the string method to split, but I prefer the Regex one, since it takes a string insted of a char[].