String extraction in C# - c#

I'm getting pretty frustrated with this, and hope the community can help me out.
I have a string, an example would be "1_ks_Males", another example would be "12_ks_Females".
What I need to do is write a method that extract's each value. So from the first example I'd want something like this:
1
ks
Males
In separate variables.
I'm sure I'm just being incredibly thick, but I just can't get it!

Simply use string.Split('_'). With your input strings it will return a string array with three elements.

You can use Split function for String. Something like this
var split = "1_ks_Males".Split('_');
var first = split[0];
var second = split[1];
var third = split[2];

You just need to use split:
var exampleString = "1_ks_Males";
var split = exampleString.split("_");
var first= split[0]; // 1
var second = split[1]; // ks
var third = split[2]; // Males

string[] array = "1_ks_Males".Split('_');
Assert.AreEqual("1",array[0])
Assert.AreEqual("ks",array[1])
Assert.AreEqual("Males",array[2])

var values = "1_ks_Males".Split('_');
// values[0]: 1
// values[1]: ks
// values[2]: Males

How about this?
var data = myString.Split("_");
var value = data[0];
var #type = data[1];
var gender = data[2];

use String.Split which returns an array of values
var values = "12_ks_Females".split("_");
// values[0] == "12"
// values[1] == "ks"
// values[2] == "Females"

You could use split -
var s = "1_ks_Males";
string[] values = s.Split('_');
Your values will then be contained in the `values' array -
var firstvalue = values[0];
var secondvalue = values[1];
var thirdvalue = values[2];

You'll want to look into the String.Split method of the String class. Here's the MSDN link.
Basically, if all of your strings have the values that you require separated by a consistent character (in your example, this is an underscore character), you can use the Split method which will split a single string into an array of new strings based upon a specific separator.
For example:
string s = "1_ks_Males";
string[] v = s.Split('_');
Console.WriteLine(v[0]);
Console.WriteLine(v[1]);
Console.WriteLine(v[2]);
would output:
1
ks
Males

You should use the String.Split method.
Like: string[] splitParts = "1_ks_Males".Split('_');

This should do the trick:
var values = myString.Split('_');

var splitVar = "1_ks_Males".Split('_');
var firstVar = splitVar[0];
var secondVar = splitVar[1];
var thirdVar = splitVar[2];

Use Split function of the string for it:
var variables = "1_ks_Males".Split(new char[]{'_'}, StringSplitOptions.IgnoreEmpty);
Now variables[0] == "1", variables[1] == "ks", and variables[2] == "Males"

You can use Split function provided by String. Read more about it # MSDN
var data = "1_ks_Males".Split('_');

Related

Insert text between 2 delimeters

I have a string that looks something like this
Say_Hi~~~Say_Opt1~~Say_Opt3~~~Say_Opt6~~~Say_Opt9~~Say_GoodBye
It has 16 '~' dividing it into 17 "sections". In section number 5, I need to insert Say_Opt5.
Say_Hi~~~Say_Opt1~~Say_Opt3~~Say_Opt5~Say_Opt6~~~Say_Opt9~~Say_GoodBye
So I need to be able to take a string, and a position, and isert the string into the position specified. I tried using a regex but im not entire sure how matches work.
string baseString = "Say_Hi~~~Say_Opt1~~Say_Opt3~~~Say_Opt6~~~Say_Opt9~~Say_GoodBye";
var newString = new Regex("~").Replace(baseString, "Say_Opt5", 7);
Also, there may already be an Option 5, so I need to replace the old option5 with the new option 5. Such as replacing
Say_Hi~~~Say_Opt1~~Say_Opt3~~Say_Opt5~Say_Opt6~~~Say_Opt9~~Say_GoodBye
with
Say_Hi~~~Say_Opt1~~Say_Opt3~~Say_Opt5_Custom~Say_Opt6~~~Say_Opt9~~Say_GoodBye
var s1 = "there~is~a~~cat";
var s2 = "super";
var words = s1.Split('~').ToList();
//words.Insert(3, s2); // this will insert new token
words[3] = s2; // this will replace word at specific index
var res = string.Join("~", words.ToArray());
After this your cat will become a super hero, it will become a super cat :)
If you are using C#, you can use this:
string s = "Say_Hi~~~Say_Opt1~~Say_Opt3~~~Say_Opt6~~~Say_Opt9~~Say_GoodBye";
MessageBox.Show(s);
string[] parts = s.Split('~');
parts[YourIntegerIndex] = "YouNewString";
s = string.Join("~", parts);
MessageBox.Show(s);

How to remove comma separated duplicated string values and get last two values

I want to remove comma separated duplicate string values like :
String str = "2,4,3,12,25,2,4,3,6,2,2,2";
And i want to output like this:
String str1 = "6,2";
please tell how to do this i'll my self but i can't solve this
A wild ride with Linq. Probably there is a better way, but this is the first one I could think of.
string str = "2,4,3,12,25,2,4,3,6,2,2,2";
List<string> uniques = str.Split(',').Reverse().Distinct().Take(2).Reverse().ToList();
string newStr = string.Join(",", uniques);
Console.WriteLine(newStr);
Split the string at the comma to get the sequence
Apply the Reverse op, you get 2 2 2 6 .... 4 2
Apply the Distinct, you get 2,6,3,4,25,12
Take the first 2 elements (2,6)
Reverse them 6,2
Join in a new string with the comma sep.
Pretty basic but works in your case
String str = "2,4,3,12,25,2,4,3,6,2,2,2";
String[] arr = str.Split(',');
String penultimate = "";
String ultimate = "";
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] != ultimate)
{
penultimate = ultimate;
ultimate = arr[i];
}
}
Console.WriteLine("{0},{1}", penultimate, ultimate);
Here is a suggestion:
string item = "";
var lastTwoUnique= str.Split(',') //split the string on ,
//now, take the next element from the array as long as it's
//not equal to the previous element (which we store in item)
.Where((st) => st==item ? false : (item = st) == item) //** see comment below
.Reverse() //reverse collection
.Take(2) //take two (two last)
.Reverse() //reverse back
.ToList(); //make it a list
var answer = string.Join(",", lastTwoUnique);
This solution keeps the data intact, so if you want you could store the unique list, then do many queries on that list. Solutions using Distinct() will, for instance, not keep every occurrence of 2 in the list.
This solution has the intermediate result (after Where) of: 2,4,3,12,25,2,4,3,6,2. While distinct will be:2,4,3,12,25,6
** The line .Where((st) => st==item ? false : (item = st) == item) may seem odd, so let me explain:
Where takes a lambda function that returns true for items that should be taken, and false for the items that should be ignored. So st will become each sub string from the Split.
Now, let's investigate the actual function:
st==item //is this st equal to the previous item?
? false //then return false
: (item = st) == item //if it's not equal, then assign `item` to the current `st`
//and compare that to item and get `true`
You could use the .Distinct() extension method.
String str = "2,4,3,12,25,2,4,3,6,2,2,2";
var oldArray=str.Split(',').Reverse();
var collectionWithDistinctElements = oldArray.Distinct().ToArray();
var reverse=collectionWithDistinctElements.Reverse();
//take two element
var twoElements=reverse.ToList().Take(2);
//last join them
var resultArray=string.Join(",", twoElements);
Another solution, which I've attempted to keep quite simple:
String str = "2,4,3,12,25,2,4,3,6,2,2,2";
var holder = new string[2];
foreach (var x in str.Split(','))
{
if(holder.Last() != x)
{
holder[0] = holder[1];
holder[1] = x;
}
}
var result = string.Join(",", holder);
This will iterate over the comma-separated items, all the time keeping the two last seen distinct items in holder.
String str = "2,4,3,12,25,2,4,3,6,2,2,2";
string str = s1;
var uniques = str.Split(',').Reverse().Distinct().Take(3).Reverse().Take(2).ToList();
string newStr = string.Join(",", uniques.ToArray());
This will give me correct output that is 3,6 thats i want.
Thanks to all the Guys that give me ans.
This will definitely work
string str = "2,4,3,12,25,2,4,3,6,2,2,2";
List<string> uniques = new List<string>()
uniques = str.Split(',').Reverse().Distinct().Take(2).Reverse().ToList();
string newStr = string.Join(",", uniques);

Unable to Split the string accordingly

I know this question would have been asked infinite number of times, but I'm kinda stuck.
I have a string something like
"Doc1;Doc2;Doc3;12"
it can be something like
"Doc1;Doc2;Doc3;Doc4;Doc5;56"
Its like few pieces of strings separated by semicolon, followed by a number or id.
I need to extract the number/id and the strings separately.
To be exact, I can have 2 strings: one having "Doc1;Doc2;Doc3" or "Doc1;Doc2;Doc3;Doc4" and the other having just the number/id as "12" or "34" or "45" etc.
And yeah I am using C# 3.5
I understand its a pretty easy and witty question, but this guy is stuck.
Assistance required from experts.
Regards
Anurag
string.LastIndexOf and string.Substring are the keys to what you're trying to do.
var str = "Doc1;Doc2;Doc3;12";
var ind = str.LastIndexOf(';');
var str1 = str.Substring(0, ind);
var str2 = str.Substring(ind+1);
One way:
string[] tokens = str.Split(';');
var docs = tokens.Where(s => s.StartsWith("Doc", StringComparison.OrdinalIgnoreCase));
var numbers = tokens.Where(s => s.All(Char.IsDigit));
String docs = s.Substring(0, s.LastIndexOf(';'));
String number = s.Substring(s.LastIndexOf(';') + 1);
One possible approach would be this:
var ids = new List<string>();
var nums = new List<string>();
foreach (var s in input.Split(';'))
{
int val;
if (!int.TryParse(s, out val)) { ids.Add(s); }
else { nums.Add(s); }
}
where input is something like Doc1;Doc2;Doc3;Doc4;Doc5;56. Now, ids will house all of the Doc1 like values and nums will house all of the 56 like values.
you can use StringTokenizer functionality.
http://www.c-sharpcorner.com/UploadFile/pseabury/JavaLikeStringTokenizer11232005015829AM/JavaLikeStringTokenizer.aspx
split string using ";"
StringTokenizer st = new StringTokenizer(src1,";");
collect final String. that will be your ID.
You may try one of two options: (assuming your input string is in string str;
Approach 1
Get LastIndexOf(';')
Split the string based on the index. This will give you string and int part.
Split the string part and process it
Process the int part
Approach 2
Split the string on ;
Run a for loop - for (int i = 0; i < str.length - 2; i++) - this is the string part
Process str[length - 1] separately - this is the int part
Please take this as a starting point as there could be other approaches to implement a solution for this
string actual = "Doc1;Doc2;Doc3;12";
int lstindex = actual.LastIndexOf(';');
string strvalue = actual.Substring(0, lstindex);
string id = actual.Substring(lstindex + 1);

Splitting a string which contain multiple symbols to get specific values

I cannot believe I am having trouble with this following string
String filter = "name=Default;pattern=%%;start=Last;end=Now";
This is a short and possibly duplicate question, but how would I split this string to get:
string Name = "Default";
string Pattern = "%%" ;
string start = "Last" ;
string end = "Now" ;
Reason why I ask is my deadline is very soon, and this is literally the last thing I must do. I'm Panicking, and I'm stuck on this basic command. I tried:
pattern = filter.Split(new string[] { "pattern=", ";" },
StringSplitOptions.RemoveEmptyEntries)[1]; //Gets the pattern
startDate = filter.Split(new string[] { "start=", ";" },
StringSplitOptions.RemoveEmptyEntries)[1]; //Gets the start date
I happen to get the pattern which I needed, but as soon as I try to split start, I get the value as "Pattern=%%"
What can I do?
Forgot to mention
The list in this string which needs splitting may not be in any particular order . this is a single sample of a string which will be read out of a stringCollection (reading these filters from Properties.Settings.Filters
Using string.Split this is a two stage process.
In the first case split on ; to get an array of keyword and value pairs:
string[] values = filter.Split(';');
Then loop over the resultant list splitting on = to get the keywords and values:
foreach (string value in values)
{
string[] pair = value.Split('=');
string key = pair[0];
string val = pair[1];
}
String filter = "name=Default;pattern=%%;start=Last;end=Now";
string[] temp = filter.Split('=');
string name = temp[1].Split(';')[0];
string pattern = temp[2].Split(';')[0];
string start = temp[3].Split(';')[0];
string end = temp[4].Split(';')[0];
This should do the trick:
string filter = "name=Default;pattern=%%;start=Last;end=Now";
// Make a dictionary.
var lookup = filter
.Split(';')
.Select(keyValuePair => keyValuePair.Split('='))
.ToDictionary(parts => parts[0], parts => parts[1]);
// Get values out of the dictionary.
string name = lookup["name"];
string pattern = lookup["pattern"];
string start = lookup["start"];
string end = lookup["end"];
The start date ends up at the thrird position in the array:
startDate = filter.Split(new string[] { "start=", ";" }, StringSplitOptions.RemoveEmptyEntries)[2];
Instead of splitting the string once for each value, you might want to split it into the separate key-value pairs, then split each pair:
string[] pairs = filter.Split(';');
string[] values = pairs.Select(pair => pair.Split('=')[1]).ToArray();
string name = values[0];
string pattern = values[1];
string start = values[2];
string end = values[3];
(This code of course assumes that the key-value pairs always come in the same order.)
You could also split the string into intersperced array, so that every other item is a key or a value:
string[] values = filter.Split(new string[] { "=", ";" }, StringSplitOptions.None);
string name = values[1];
string pattern = values[3];
string start = values[5];
string end = values[7];
Edit:
To handle key-values in any order, make a lookup from the string, and pick values from it:
ILookup<string, string> values =
filter.Split(';')
.Select(s => s.Split('='))
.ToLookup(p => p[0], p => p[1]);
string name = values["name"].Single();
string pattern = values["pattern"].Single();
string start = values["start"].Single();
string end = values["end"].Single();
You can use SingleOrDefault if you want to support values being missing from the string:
string name = values["name"].SingleOrDefault() ?? "DefaultName";
The lookup also supports duplicate key-value pairs. If there might be duplicates, just loop through the values:
foreach (var string name in values["name"]) {
// do something with the name
}
Well I tried something like this:
var result = "name=Default;pattern=%%;start=Last;end=Now".Split(new char[]{'=',';'});
for(int i=0;i<result.Length; i++)
{
if(i%2 == 0) continue;
Console.WriteLine(result[i]);
}
and the output is:
Default
%%
Last
Now
Is this what you want?
You see, the thing is now that your Split on filter a second time still starts from the beginning of the string, and it matches against ;, so since the string hasn't changed, you still retrieve previous matches (so your index accessor is off by X).
You could break this down into it's problem parts, such that:
var keyValues = filter.Split(';');
var name = keyValues[0].Split('=')[1];
var pattern = keyValues[1].Split('=')[1];
var start = keyValues[2].Split('=')[1];
var end = keyValues[3].Split('=')[1];
Note that the above code is potentially prone to error, and as such should be properly altered.
You can use the following:
String filter = "name=Default;pattern=%%;start=Last;end=Now";
string[] parts = filter.Split(';');
string Name = parts[0].Substring(parts[0].IndexOf('=') + 1);
string Pattern = parts[1].Substring(parts[1].IndexOf('=') + 1);
string start = parts[2].Substring(parts[2].IndexOf('=') + 1);
string end = parts[3].Substring(parts[3].IndexOf('=') + 1);
Use this:
String filter = "name=Default;pattern=%%;start=Last;end=Now";
var parts = filter.Split(';').Select(x => x.Split('='))
.Where(x => x.Length == 2)
.Select(x => new {key = x[0], value=x[1]});
string name = "";
string pattern = "";
string start = "";
string end = "";
foreach(var part in parts)
{
switch(part.key)
{
case "name":
name = part.value;
break;
case "pattern":
pattern = part.value;
break;
case "start":
start = part.value;
break;
case "end":
end = part.value;
break;
}
}
If you don't need the values in named variables, you only need the second line. It returns an enumerable with key/value pairs.
My solution has the added benefits that the order of those key/value pairs in the string is irrelevant and it silently ignores invalid parts instead of crashing.
I found a simple solution on my own too. Most of your answers would have worked if the list would have been in the same order every single time, but it wont be. the format however, will always stay the same. The solution is a simple iteration using a foreach loop, and then checking if it starts with a certain word, namely, the word I am looking for, like Name, Pattern etc.
Probably not the most cpu efficient way of doing it, but it is C# for dummies level. Really brain-fade level.
Here is my beauty.
foreach (string subfilter in filter.Split(';')) //filter.Split is a string [] which can be iterated through
{
if (subfilter.ToUpper().StartsWith("PATTERN"))
{
pattern = subfilter.Split('=')[1];
}
if (subfilter.ToUpper().StartsWith("START"))
{
startDate = subfilter.Split('=')[1];
}
if (subfilter.ToUpper().StartsWith("END"))
{
endDate = subfilter.Split('=')[1];
}
}

array of char to string in c#

I have a string that looks like a phone number. I'm using a lambda to extract an array of char. Then I want to convert this array into a string. This is what I have:
PhoneCandidate = "(123)-321-1234"; //this is just an example of what it could look like
var p = PhoneCandidate.Where(c => char.IsDigit(c)).ToArray();
string PhoneNumber = p.toString();
However, when I run this code, the variable PhoneNumber becomes just "System.Char[]" instead of the values inside the array.
What do I need to change?
Thanks.
You can use the string constructor that takes a char[].
string PhoneNumber = new string(p);
string phone = new string(p);
Try with constructor res = new string(yourArray);
One of the string constructors takes a char[]:
string PhoneNumber = new string(p);
Let's take this a whole new direction:
Dim digits as New Regex(#"\d");
string phoneNumber = digits.Replace(PhoneCandidate, "");
Assuming p is a char[] you can use the following:
String phoneNumber = new String(p);
probably the best bet is to use the string constructor per (#Adam Robinson) however as an alternative, you can also use string.Join(string separator,params string[] value)
(MSDN docs here)
PhoneCandidate = "(123)-321-1234"; //this is just an example of what it could look like
var p = PhoneCandidate.Where(c => char.IsDigit(c)).ToArray();
string str = string.Join(string.Empty,p);

Categories

Resources