Parsing similar named parameters out of a URL - c#

I'm taking a URL that looks like this:
some_site.com/full/path/page.aspx?label[0]=a_value&label[1]=b_value&label[2]=c_value
The indexed number is generated, so there's a dynamic number of these 'label[x]' values every time.
What would the simplest way of parsing these all into a String[] named 'Label' in ASP/C#.NET 4.0?

You should use a NameValueCollection instead of array of Strings.
NameValueCollection queryParameters = new NameValueCollection();
string[] querySegments = queryString.Split('&');
foreach(string segment in querySegments)
{
string[] parts = segment.Split('=');
if (parts.Length > 0)
{
string key = parts[0].Trim(new char[] { '?', ' ' });
string val = parts[1].Trim();
queryParameters.Add(key, val);
}
}
To get the number of the label withing the square brackets, use Regular Expressions.
regxObj = new Regex(#"\[(.*?)\]");

Have you thought about enumerating the entries in the Request.Querystring collection?

You can start by taking the substring from the index of '?' to the end, then split by '&'.
Then you can either loop through that list and split by '=' and take the second element, or the substring of each of those starting after the index of '='.
If you do want it as just and array of strings for some reason, this one line will probably work.
String[] labels = (from substring in s.Substring(s.IndexOf('?') + 1).Split('&') select substring.Substring(substring.IndexOf('=') + 1)).ToArray();
edit: Do note that this disregards what the actual labels are, as well as their numbers; if there's something other than named, numbered label[n] tags, those will be added as to the array as well.

make a parameter called length
some_site.com/full/path/page.aspx?length=4&label[0]=a_value&label[1]=b_value&label[2]=c_value...
then that will be easy to parse on the other side already knowing the length
if you know the length , then you know how many times to iterate through a loop to read the values of querystring
-or-
don't have a variable amount of parametes , use one , and use any special character to seperate them, then split the value by the seperating char on the other side

Related

Adding numbers from list of custom delimieters

I am writing program to add numbers from string which will be seperated from delimeters
private static readonly char[] Separators = { ',', '\n', '/','#' };
public int Add(string numbers)
{
if (numbers.Equals(string.Empty))
{
return 0;
}
return numbers.Split(Separators).Select(int.Parse).Sum();
}
When i pass the following string to Add method //#\n2#3
Then i get below error Input string was not in a correct format.
I expect answer to be 5
By default, string.Split will create empty groups if two delimiters are right next to each other. For example "3,,4".Split(','); will produce an array with three elements ("3", empty string, and "4").
You can change this in one of two ways. The first (and probably simpler) is to have the Split ignore empty entries.
numbers.Split(Separators, StringSplitOptions.RemoveEmptyEntries)
Or you can use Where in Linq
numbers.Split(Separators).Where(x => x.Length > 0)
This will prevent elements with a blank string value reaching int.Parse. Of course, there are still other things you should do to validate your input before attempting to parse, but that's another topic.

Split string with plus sign as a delimiter

I have an issue with a string containing the plus sign (+).
I want to split that string (or if there is some other way to solve my problem)
string ColumnPlusLevel = "+-J10+-J10+-J10+-J10+-J10";
string strpluslevel = "";
strpluslevel = ColumnPlusLevel;
string[] strpluslevel_lines = Regex.Split(strpluslevel, "+");
foreach (string line in strpluslevel_lines)
{
MessageBox.Show(line);
strpluslevel_summa = strpluslevel_summa + line;
}
MessageBox.Show(strpluslevel_summa, "summa sumarum");
The MessageBox is for my testing purpose.
Now... The ColumnPlusLevel string can have very varied entry but it is always a repeated pattern starting with the plus sign.
i.e. "+MJ+MJ+MJ" or "+PPL14.1+PPL14.1+PPL14.1" as examples.
(It comes form Another software and I cant edit the output from that software)
How can I find out what that pattern is that is being repeated?
That in this exampels is the +-J10 or +MJ or +PPL14.1
In my case above I have tested it by using only a MessageBox to show the result but I want the repeated pattering stored in a string later on.
Maybe im doing it wrong by using Split, maybe there is another solution.
Maybe I use Split in the wrong way.
Hope you understand my problem and the result I want.
Thanks for any advice.
/Tomas
How can I find out what that pattern is that is being repeated?
Maybe i didn't understand the requirement fully, but isn't it easy as:
string[] tokens = ColumnPlusLevel.Split(new[]{'+'}, StringSplitOptions.RemoveEmptyEntries);
string first = tokens[0];
bool repeatingPattern = tokens.Skip(1).All(s => s == first);
If repeatingPattern is true you know that the pattern itself is first.
Can you maybe explain how the logic works
The line which contains tokens.Skip(1) is a LINQ query, so you need to add using System.Linq at the top of your code file. Since tokens is a string[] which implements IEnumerable<string> you can use any LINQ (extension-)method. Enumerable.Skip(1) will skip the first because i have already stored that in a variable and i want to know if all others are same. Therefore i use All which returns false as soon as one item doesn't match the condition(so one string is different to the first). If all are same you know that there is a repeating pattern which is already stored in the variable first.
You should use String.Split function :
string pattern = ColumnPlusLevel.Split("+")[0];
...but it is always a repeated pattern starting with the plus sign.
Why do you even need String.Split() here if the pattern always only repeats itself?
string input = #"+MJ+MJ+MJ";
int indexOfSecondPlus = input.IndexOf('+', 1);
string pattern = input.Remove(indexOfSecondPlus, input.Length - indexOfSecondPlus);
//pattern is now "+MJ"
No need of string split, no need to use LinQ
String has a method called Split which let's you split/divide the string based on a given character/character-set:
string givenString = "+-J10+-J10+-J10+-J10+-J10"'
string SplittedString = givenString.Split("+")[0] ///Here + is the character based on which the string would be splitted and 0 is the index number
string result = SplittedString.Replace("-","") //The mothod REPLACE replaces the given string with a targeted string,i added this so that you can get the numbers only from the string

Array failed to know if it contains a string

I must doing something wrong... But I can't figure it out!
I have an array with string in it. I'm trying to fins if the Array contains some words like Sales for example.
drillDownUniqueNameArray[0] = "[Sales Territory].[Sales Territories].[Sales Territory Group].&[North America]";//Inside the string array there is this string in index 0
drillDownUniqueNameArray.Contains("S")//Output false!
Array.IndexOf(drillDownUniqueNameArray,"S")//Output -1! <--Fixed My answer
drillDownUniqueNameArray.Contains("[Sales Territory].[Sales Territories].[Sales Territory Group].&[North America]") //Output true!
I thouhgt Contains should find even part of the string..
How can I find if this array have "S" or "Sales" for example?
You are asking if the array contains a string that exactly matches "S".
What you want is to ask if any of the strings in the array contains the character "S", something like:
drillDownUniqueNameArray.Any(v => v.Contains("S"))
You're checking if the array contains an element that's exactly "S" but I think you are trying to check whether the array contains an alement that contains an "S".
You could achieve this by the following statement:
drillDownUniqueNameArray.Any( str => str.Contains ("S") )
You can try this.
drillDownUniqueNameArray[0].Contains("s");
You can use LINQ:
var allWithSales = drillDownUniqueNameArray
.Where(str => str.Contains("Sales"));
ignoring the case:
var allWithSalesIgnoreCase = drillDownUniqueNameArray
.Where(str => str.IndexOf("sales", StringComparison.OrdinalIgnoreCase) >= 0);
If you want to find all that contain a word "Sales"(String.Split() = white-space delimiter)):
var allWordsWithSales = drillDownUniqueNameArray
.Where(str => str.Split().Contains("Sales", StringComparer.OrdinalIgnoreCase));
Now you can enumerate the query with foreach or use ToArray() or ToList to create a collection:
foreach(string str in allWithSales)
Console.WriteLine(str);
You are finding it in the array, but you should find the word in the string.
Use following if you want to check:
drillDownUniqueNameArray.Any(x=>x.Contains("Sales"));
Use following if want to get the strings which contains "Sales"
drillDownUniqueNameArray.Where(x=>x.Contains("Sales"));
When you do it like this:
drillDownUniqueNameArray.Contains("S")
it's not gonna check the values, you must do it like this:
drillDownUniqueNameArray[0].Contains("S") or drillDownUniqueNameArray.First().Contains("S")
like this way it checks the values inside the array not the arrays itself

Length of array created by using split string

I know that we can use string.split() to put our data into arrays like below:
string[] strSplit = Data.Split('|');
But can we know how many array items it created? I need that number.
It will create a single array of multiple strings. Like T.S. commented, you can get the number of strings using the length property of the returned array
int length = strSplit.length
Sometime you need remove the empty entries in spilt result:
string[] strSplit = data.Split(new []{"|"}, StringSplitOptions.RemoveEmptyEntries);
And get the length like this:
int length = strSplit.Length;

Copy first few strings separated by a symbol in c#

I have a string consist of integer numbers followed by "|" followed by some binary data.
Example.
321654|<some binary data here>
How do i get the numbers in front of the string in the lowest resource usage possible?
i did get the index of the symbol,
string s = "321654654|llasdkjjkwerklsdmv"
int d = s.IndexOf("|");
string n = s.Substring(d + 1).Trim();//did try other trim but unsuccessful
What to do next? Tried copyto but copyto only support char[].
Assuming you only want the numbers before the pipe, you can do:
string n = s.Substring(0, d);
(Make it d + 1 if you want the pipe character to also be included.)
I might be wrong, but I think you are under the impression that the parameter to string.Substring(int) represents "length." It does not; it represents the "start-index" of the desired substring, taken up to the end of the string.
s.Substring(0,d);
You can use String.Split() here is a reference http://msdn.microsoft.com/en-us/library/ms228388%28VS.80%29.aspx
string n = (s.Split("|"))[0] //this gets you the numbers
string o = (s.Split("|"))[1] //this gets you the letters

Categories