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);
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 have a string which is
string a = #"\server\MainDirectory\SubDirectoryA\SubDirectoryB\SubdirectoryC\MyFile.pdf";
The SubDirectoryB will always start with a prefix of RN followed by 6 unique numbers. Now I'm trying to modify SubDirectoryB parth of the string to be replaced by a new value lets say RN012345
So the new string should look like
string b = #"\server\MainDirectory\SubDirectoryA\RN012345\SubdirectoryC\MyFile.pdf";
To achieve this I'm making use of the following helper method
public static string ReplaceAt(this string path, int index, int length, string replace)
{
return path.Remove(index, Math.Min(length, path.Length - index)).Insert(index, replace);
}
Which works great for now.
However the orginial path will be changing in the near future so it will something like #\MainDirectory\RN012345\AnotherDirectory\MyFile.pdf. So I was wondering if there is like a regex or another feature I can use to just change the value in the path rather than providing the index which will change in the future.
Assuming you need to only replace those \RNxxxxxx\ where each x is a unique digit, you need to capture the 6 digits and analyze the substring inside a match evaluator.
var a = #"\server\MainDirectory\SubDirectoryA\RN012345\SubdirectoryC\MyFile.pdf";
var res = Regex.Replace(a, #"\\RN([0-9]{6})\\", m =>
m.Groups[1].Value.Distinct().Count() == m.Groups[1].Value.Length ?
"\\RN0123456\\" : m.Value);
// res => \server\MainDirectory\SubDirectoryA\RN0123456\SubdirectoryC\MyFile.pdf
See the C# demo
The regex is
\\RN([0-9]{6})\\
It matches a \ with \\, then matches RN, then matches and captures into Group 1 six digits (with ([0-9]{6})) and then will match a \. In the replacment part, the m.Groups[1].Value.Distinct().Count() == m.Groups[1].Value.Length checks if the number of distinct digits is the same as the number of the substring captured, and if yes, the digits are unique and the replacement occurs, else, the whole match is put back into the replacement result.
Use String.Replace
string oldSubdirectoryB = "RN012345";
string newSubdirectoryB = "RN147258";
string fileNameWithPath = #"\server\MainDirectory\SubDirectoryA\RN012345\SubdirectoryC\MyFile.pdf";
fileNameWithPath = fileNameWithPath.Replace(oldSubdirectoryB, newSubdirectoryB);
You can use Regex.Replace to replace the SubDirectoryB with your required value
string a = #"\server\MainDirectory\SubDirectoryA\RN123456\SubdirectoryC\MyFile.pdf";
a = Regex.Replace(a, "RN[0-9]{6,6}","Mairaj");
Here i have replaced a string with RN followed by 6 numbers with Mairaj.
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();
}
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.