Extract part of querystring using visual basic - c#

I have a querystring:
...default.aspx?date=May%202012
I want to get may and 2012 separately from that using:
Request.querystring("date")
....something similar for each.
Is this possible?

You can use HttpUtility.UrlDecode:
Dim dateParam = HttpUtility.UrlDecode(Request.QueryString("date"))
Dim dateParts = dateParam.Split(" "c)
Dim month = dateParts(0)
Dim year = dateParts(1)
C#
var dateParam = HttpUtility.UrlDecode(Request.QueryString["date"]);
var dateParts = dateParam.Split(' ');
var month = dateParts[0];
var year = dateParts[1];
Edit: As #Servy has commented HttpUtility.UrlDecode is redundant above since Request.QueryString decodes it implicitely, but it doesn't hurt ;-)

Related

How should we reverse format & extract a string in C#?

Pretty sure we all do string.format and define some string in a specifed format.
I have a string which is always formatted in a way like this:
const string myString = string.Format("pt:{0}-first:{1}", inputString);
To get {0}, I can always check for pt:{ and read till }.
But what is the best/recommended way to extract {0} & {1} from the above variable myString ?
A Regex version of answer, but again, assuming your input doesnt contain '-'
var example = = "pt:hello-first:23";
var str = "pt:(?<First>[^-]+)-first:(?<Second>[^%]+)";
var match = new Regex(str).Match(example);
var first = match.Groups["First"].Value;
var second = match.Groups["Second"].Value;
It might be a good idea that you define what your variable can/cannot contain.
Not sure if this is the best way to do it, but it's the most obvious:
string example = "pt:123-first:456";
var split = example.Split('-');
var pt = split[0].Substring(split[0].IndexOf(':') + 1);
var first = split[1].Substring(split[1].IndexOf(':') + 1);
As Shawn said, if you can guarantee that the variables wont contain either : or - this will be adequate.

C# String Format give wrong result

I'm trying to format a string of 6 digits with the following format:
1234/56.
I'm using the following:
string.Format("123456", "{0000/00}");
Result 123456
Try something like
var number = int.Parse("123456");
var formattedNumber = number.ToString("####/##", CultureInfo.InvariantCulture);
Edit to include zero fill (if required):
var number = int.Parse("123456");
var formattedNumber = number.ToString("####/##", CultureInfo.InvariantCulture).PadLeft(7,'0');
You will still have issues with any number below 10 (i.e "000009") showing up as 0000/9. In which you are probably better off with a substring modification like below.
var text = "123456";
var formattedNumber = text.Substring(0, 4) + "/" + text.Substring(4, 2);
Please try the below code.
string.Format("{0:####/##}",123456)
I tested the code and is working.
For reference on string formatting please visit:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings
If you are using numbers I would use #rob-s 's example above. If you are dealing with actual strings then you can use the following code sample.
var value = "123456";
var index = value.Length - 2;
var formattedValue = $"{value.Substring(0, index)}/{value.Substring(index)}";
Console.WriteLine(formattedValue);
Your output will look like what you have described in your question.
1234/56

Converting strings to arrays c#

I have manipulated a string into the following format:
Type___Product___State___Form___Qty____someType___someProduct___someState___someForm___someQty____someOtherType___someOtherProduct...
(3 underscores between values, 4 underscores representing a line break if this was a table)
What I need to do is Create 5 string arrays (string[] type, string [] product, ...)
that pull every 5th value string into it.
So example:
string[] type = {someType, someOtherType, someOtherOtherType,...}
Any help or tips would be greatly appreciated. Thanks!
This should give you an idea on how to work with the strings.
Private Sub SplitStrings(s As String)
Dim lines() As String = Split(s, "____")
For Each line As String In lines
Dim perLineTokens() As String = line.Split("___")
Next
End Sub
The functionality you need exists in this code example, but you'll need to review it and make modifications for it to fit your exact requirements (hint: % operator would be useful). Let me know if you have questions.
const string test = "Type___Product___State___Form___Qty____someType___someProduct___someState___someForm___someQty____someOtherType___someOtherProduct___someOtherState___someOtherForm___someOtherQty";
var lines = Regex.Split(test, "____");
var strings = new string[lines.Length, 5];
var lineIteration = 0;
foreach (var line in lines)
{
var values = Regex.Split(line, "___");
var valueIteration = 0;
foreach (var value in values)
{
strings[lineIteration, valueIteration] = value;
valueIteration++;
}
lineIteration++;
}

C# Skipwhile to VB skipWhile

I have code in C#
string fileNameOnly = Path.GetFileNameWithoutExtension(sKey);
string token = fileNameOnly.Remove(fileNameOnly.LastIndexOf('_'));
string number = new string(token.SkipWhile(Char.IsLetter).ToArray());
And i want it in VB
Dim fileNameOnly As String = Path.GetFileNameWithoutExtension(sKey)
Dim token As String = fileNameOnly.Remove(fileNameOnly.LastIndexOf("_"c))
Dim number As New String(token.SkipWhile([Char].IsLetter).ToArray())
I have tried that but did not work! Is there something similar to use.
What it does is look at a file name and only use the number part of it and skip all letters and all after _.
You have to use AddressOf in VB.NET:
Dim number As New String(token.SkipWhile(AddressOf Char.IsLetter).ToArray())
You could also use Function:
Dim number As New String(token.SkipWhile(Function(c)Char.IsLetter(c)).ToArray())
In VB.NET i often use multiple lines and combine query+method syntax to avoid the ugly Function/AddressOf keywords.
Dim numberChars = From c In token
Skip While Char.IsLetter(c)
Dim numbers = New String(numberChars.ToArray())

how to extract string from certain position

I am struggling to find a solution in string manipulation - I am trying to extract a certain part of the string element after the '=' character - say for ex.
dim s as string = "/mysite/secondary.aspx?id=1005"
I am trying to get the string after the "=" and just to grab the 1005. I tried indexof and split, but i am not sure where i am going wrong. Any help, please?
Here is what i did:
Dim lnk As String = "/mysite/secondary.aspx?id=1005"
Dim id As Long = lnk.IndexOf("=")
Dim part As String = lnk.Substring(id + 1, 4)
Thanks
Try the following
Dim index = s.IndexOf("="C)
Dim value = s.Substring(index + 1)
This will put "1005" into value
Dim tUriPath As String = "/mysite/secondary.aspx?id=1005"
Dim tURI As Uri = New Uri("dummy://example.com" & tUriPath)
Dim tIdValue As String = System.Web.HttpUtility.ParseQueryString(tUri.Query)("id")
Here's a very simple example. Obviously it relies on very specific conditions:
Dim afterEquals As String = s.Split("="c)(1)
You would probably want something slightly more robust (checking to make sure more than one string was returned from Split, etc.).
If you try string.Split with '=' you'll get 1005 on the first element of the array and the /mysite/secondary.aspx?id= on the 0th position.
But if this is just a regular URL coming from an http request.
You could possibly do Request.QueryString("id") and it will return 1005;
Borrowing code from Boo...
Dim tUriPath As String = "/mysite/secondary.aspx?id=1005"
Dim tURI As Uri = New Uri("dummy://example.com" & tUriPath)
Dim tIdValue As String = System.Web.HttpUtility.ParseQueryString(tUri.Query)
Dim theIntYouWant as String= System.Web.HttpUtility.ParseQueryString(tUri.Query)("id")

Categories