ToString Format - c#

I have an String like this "00.00-0-00" and I need to transform like this "0000-0/00"
I already tried:
field.ToString("####-##/##") ' without success
String.Format(CultureInfo.InvariantCulture, "{0:####-#/##}", field) 'without success
Any help with that?

My version which work if your original format doesn't change(as other answers based too)
Dim oldString As String = "00.00-0-00"
Dim parts As String() = oldString.Split({"."c, "-"c})
Dim result As String = _
String.Format("{0}{1}-{2}/{3}", parts(0), parts(1), parts(2), parts(3)))
C# version
string original = "00.00-00-00";
string[] parts = original.Split(new char[] {'.', '-'});
string result = String.Format("{0}{1}-{2}/{3}", parts[0], parts[1], parts[2], parts[3]));

Here is how I would do it (val is input string)
string.Format(#"{0}{1}-{2}/{3}",
val.Substring(0,2),
val.Substring(3,2),
val.Substring(6,1),
val.Substring(8,2));
If you don't like string.Format you could also use concatenation (+)

If your format is always "00.00-0-00", then you can use Regex.Replace() like this:
VB.NET
Dim data As String = "00.00-0-00"
Console.WriteLine(Regex.Replace(data, "(\d+)\.(\d+)-(\d+)-(\d+)", "$1$2-$3/$4"))
C#
string data = "00.00-0-00";
Console.WriteLine(Regex.Replace(data, "(\\d+)\\.(\\d+)-(\\d+)-(\\d+)", "$1$2-$3/$4"));
Results:
0000-0/00
The Regex is capturing all of the digits into groups and you just put the groups back together with whatever delimiter you want.

If you know that your string will always be in the format, you could just do it manually. If you need to do this a lot, you could just create a function to do it.
Dim oldString As String = "00.00-0-00"
Dim newString As String = MakeNewString(oldString)
Function to call:
Function MakeNewString(oldString As String) As String
Dim noPeriod As String = Replace(oldString, ".", "")
Return Split(noPeriod, "-")(0) & "-" & Split(noPeriod, "-")(1) & "/" & Split(noPeriod, "-")(2)
End Function
In C#:
string oldString = "00.00-0-00";
string newString = MakeNewString(oldString);
C# Function:
public string MakeNewString(string oldString)
{
string noPeriod = Strings.Replace(oldString, ".", "");
return Strings.Split(noPeriod, "-")(0) + "-" + Strings.Split(noPeriod, "-")(1) + "/" + Strings.Split(noPeriod, "-")(2);
}

Related

Substring a string in C#

I want to breakdown the string as searchText. The code is shown below:
"asarrivalFDate=06/12/2017arrivalTDate=20/12/2017" as
agentName= "as"
arrivalFDate= "06/12/2017"
arrivalTDate="20/12/2017".
How can I achieve in C#. Here "as" can be any input entered by user.
I want to break and pass individual to Linq.
This code could help you:
string input = "asarrivalFDate=06/12/2017arrivalTDate=20/12/2017";
string wordToRemove1 = "arrivalFDate";
string wordToRemove2 = "arrivalTDate";
input = input.Remove(input.IndexOf(wordToRemove1), wordToRemove1.Length);
input = input.Remove(input.IndexOf(wordToRemove2), wordToRemove2.Length);
string[] inputSplitted = input.Split('=');
string agentName = inputSplitted[0];
string arrivalFDate = inputSplitted[1];
string arrivalTDate = inputSplitted[2];
I am removing the arrivalFDate and the arrivalTDate from your string, and then I split the remaining part of your string with input.Split('='). Now you get a string array string[] inputSplitted that holds your desired values (agentName,arrivalFDate,arrivalTDate) from the input string.
Without using RegEx and just using Split
Note : Assuming the format is always the same
Code
var input = "asarrivalFDate=06/12/2017arrivalTDate=20/12/2017";
var result = input.Split(
new[]
{
"arrivalFDate=",
"arrivalTDate="
},
StringSplitOptions.None);
string agentName = result[0];
string arrivalFDate = result[1];
string arrivalTDate = result[2];
Console.WriteLine(agentName);
Console.WriteLine(arrivalFDate);
Console.WriteLine(arrivalTDate);
Output
as
12/6/2017
12/20/2017

string replace but only if not contained within 2 other strings

Imagine I have a string like:
xxxstrvvv string xxxstringvvv str I am string for testing.
I want to find and replace all instances of str with xxxstrvvv that are not already contained in a xxxvvv.
so the result would be:
xxxstrvvv xxxstrvvving xxxstringvvv xxxstrvvv I am xxxstrvvving for testing
Anyone know an easy way to do this?
Edit: I want to add another situation to clarify.
xxxabcstrefgvvv
it should NOT replace this because the str is contained in xxxvvv
I suggest using regular expression with negative looking ahead and behind:
string source = "xxxstrvvv string xxxstringvvv str I am string for testing.";
string result = Regex.Replace(source, #"(?<!xxx)str(?!vvv)", "xxxstrvvv");
Edit: Same method, but a bit different pattern for the edited question:
string result = Regex.Replace(
source,
#"(?<!xxx[a-zA-Z]*)str(?![a-zA-Z]*vvv)", "xxxstrvvv");
Outcomes:
source = "xxxstrvvv string xxxstringvvv str I am string for testing.":
xxxstrvvv xxxstrvvving xxxstringvvv xxxstrvvv I am xxxstrvvving for testing.
source = "xxxabcstrefgvvv":
xxxabcstrefgvvv
Ok, I agreed with the answer of Dmitry Bychenko about Regular Expressions.
But, if your request is limited to the requirement on your answer we can use this code:
string val = "xxxstrvvv string xxxstringvvv str I am string for testing.";
val = val.Replace("xxxstringvvv", "str");
val = val.Replace("str","xxxstringvvv");
I'd go with the regex, but if you want to use replaces, this would work, if you don't have "xxxxxxstrvvvvvv" in your initial string and want to keep them that way:
string findString = "str";
string addBefore = "xxx";
string addAfter = "xxx";
string myString = "xxxstrvvv string xxxstringvvv str I am string for testing.";
myString = myString.Replace(findString, addBefore+findString+addAfter);
myString = myString.Replace(addBefore+addBefore+findString+addAfter+addAfter, addBefore+findString+addAfter);
Yes; it is ugly. I just basically do that in Notepad++ all the time with ctrl-H.
I have written a script in Python. I think you would be able to convert it to C#.
one_line = 'xxxstrvvv string xxxstringvvv str I am string for testing'
final_str = ""
arry_len = one_line.split(" ")
for ch in arry_len:
if 'str' in ch:
if not 'xxxstrvvv' in ch:
ch = ch.replace("str","xxxstrvvv")
final_str = final_str + " " + ch
print final_str

Splitting data with Regex (Regular Expressions)

I would need some help with matching data in this example string:
req:{REQUESTER_NAME},key:{abc},act:{UPDATE},sku:{ABC123,DEF-123},qty:{10,5}
Essentially, every parameter is separated by "," but it is also included within {} and I need some help with regex as I am not that good with it.
Desired Output:
req = "REQUESTER_NAME"
key = "abc"
act = "UPDATE"
sku[0] = "ABC123"
sku[1] = "DEF-123"
qty[0] = 10
qty[1] = 5
I would suggest you do the following
Use String Split with ',' character as the separator (eg output req:{REQUESTER_NAME})
With each pair of data, do String Split with ';' character as the separator (eg output "req", "{REQUESTER_NAME}")
Do a String Replace for characters '{' and '}' with "" (eg output REQUESTER_NAME)
Do a String Split again with ',' character as separator (eg output "ABC123", "DEF-123")
That should parse it for you perfectly. You can store the results into your data structure as the results come in. (Eg. You can store the name at step 2 whereas the value for some might be available at Step 3 and for others at Step 4)
Hope That Helped
Note:
- If you don't know string split - http://www.dotnetperls.com/split-vbnet
- If you don't know string replace - http://www.dotnetperls.com/replace-vbnet
The below sample may helps to solve your problem. But here lot of string manipulations are there.
string input = "req:{REQUESTER_NAME},key:{abc},act:{UPDATE},sku:{ABC123,DEF-123},qty:{10,5}";
Console.WriteLine(input);
string[] words = input.Split(new string[] { "}," }, StringSplitOptions.RemoveEmptyEntries);
foreach (string item in words)
{
if (item.Contains(':'))
{
string modifiedString = item.Replace(",", "," + item.Substring(0, item.IndexOf(':')) + ":");
string[] wordsColl = modifiedString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string item1 in wordsColl)
{
string finalString = item1.Replace("{", "");
finalString = finalString.Replace("}", "");
Console.WriteLine(finalString);
}
}
}
First, use Regex.Matches to get the parameters inside { and }.
string str = "req:{REQUESTER_NAME},key:{abc},act:{UPDATE},sku:{ABC123,DEF-123},qty:{10,5}";
MatchCollection matches = Regex.Matches(str,#"\{.+?\}");
string[] arr = matches.Cast<Match>()
.Select(m => m.Groups[0].Value.Trim(new char[]{'{','}',' '}))
.ToArray();
foreach (string s in arr)
Console.WriteLine(s);
output
REQUESTER_NAME
abc
UPDATE
ABC123,DEF-123
10,5
then use Regex.Split to get the parameter names
string[] arr1 = Regex.Split(str,#"\{.+?\}")
.Select(x => x.Trim(new char[]{',',':',' '}))
.Where(x => !string.IsNullOrEmpty(x)) //need this to get rid of empty strings
.ToArray();
foreach (string s in arr1)
Console.WriteLine(s);
output
req
key
act
sku
qty
Now you can easily traverse through the parameters. something like this
for(int i=0; i<arr.Length; i++)
{
if(arr1[i] == "req")
//arr[i] contains req parameters
else if(arr1[i] == "sku")
//arr[i] contains sku parameters
//use string.Split(',') to get all the sku paramters and process them
}
Kishore's answer is correct. This extension method may help implement that suggestion:
<Extension()>
Function WideSplit(InputString As String, SplitToken As String) As String()
Dim aryReturn As String()
Dim intIndex As Integer = InputString.IndexOf(SplitToken)
If intIndex = -1 Then
aryReturn = {InputString}
Else
ReDim aryReturn(1)
aryReturn(0) = InputString.Substring(0, intIndex)
aryReturn(1) = InputString.Substring(intIndex + SplitToken.Length)
End If
Return aryReturn
End Function
If you import System.Runtime.CompilerServices, you can use it like this:
Dim stringToParse As String = "req:{REQUESTER_NAME},key:{abc},act:{UPDATE},sku:{ABC123,DEF-123},qty:{10,5}"
Dim strTemp As String
Dim aryTemp As String()
strTemp = stringToParse.WideSplit("req:{")(1)
aryTemp = strTemp.WideSplit("},key:{")
req = aryTemp(0)
aryTemp = aryTemp(1).WideSplit("},act:{")
key = aryTemp(0)
'etc...
You may be able do this more memory efficiently, though, as this method creates a number of temporary string allocations.
Kishore's solution is perfect, but here is another solution that works with regex:
Dim input As String = "req:{REQUESTER_NAME},key:{abc},act:{UPDATE},sku:{ABC123,DEF-123},qty:{10,5}"
Dim Array = Regex.Split(input, ":{|}|,")
This does essentially the same, it uses regex to split on :{, } and ,. The solution might be a bit shorter though. The values will be put into the array like this:
"req", "REQUESTER_NAME","", ... , "qty", "10", "5", ""
Notice after the parameter and its value(s) there will be an empty string in the array. When looping over the array you can use this to let the program know when a new parameter starts. Then you can create a new array/data structure to store its values.

Replace all " and ' from a string

I want to replace all the " and ' from a string
eg strings
"23423dfd
"'43535fdgd
""'4353fg
""'''3453ere
the result should be
23423dfd
43535fdgd
4353fg
3453ere
I tried this myString.Replace("'",string.Empty).Replace('"',string.Empty); but its not giving me the correct result.
Use String.Replace
mystring = mystring.Replace("\"", string.Empty).Replace("'", string.Empty)
Do two replaces:
s = s.Replace("'", "").Replace("\"", "");
Try this:
string s = yoursting.Replace("\"", string.Empty).Replace("'", string.Empty);

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