Substring a string in C# - 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

Related

better ways to combine two array items into one string

Hello Please could you suggest better ways of writing this C# code.
Basically when NumberList has missing values between '-' I am trying to rebuild the String with default Values.
The final result should be "123-10-45-9-09"
As you can see value of "second-10" is replaced as the second item in the string.
10, 9 and 09 are filled in from the value string values.
This is the bad string which is missing some values.
string NumberList = "123--45--";
I have stored this string value in my app.config file.
string valuestring = "first-12,second-10,third-99,fourth-9,fifth-09";
protected string MissingNumberString(string Number)
{
string NumberList = "123--45--";
string valuestring = "first-12,second-10,third-99,fourth-9,fifth-09";
var companyAccountList = valuestring.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var result = NumberList.Split('-');
int counter = 0;
var builder = new System.Text.StringBuilder();
foreach (string s in companyAccountList)
{
string t = s.Substring(s.IndexOf('-') + 1);
if (string.IsNullOrEmpty(result[counter]))
builder.Append(t).Append("-");
else
{
if (companyAccountList.Length == counter)
builder.Append(result[counter]);
else
builder.Append(result[counter]).Append("-");
}
counter++;
}
return builder.ToString();
}
One way (assuming valuestring is in order and do not miss any defaults) to achieve this would be
string MissingNumber(string Number)
{
string valuestring = "first-12,second-10,third-99,fourth-9,fifth-09";
var regex = Regex.Matches(valuestring,#"(?<=-)(\d*)(?<=,)?");
var defaults = regex.Cast<Match>().Select(x=>x.Value).ToList();
var newArray = Number.Split('-').Select((x,index)=>string.IsNullOrEmpty(x)?defaults[index]:x);
return string.Join("-",newArray);
}
The code uses Regular Expression to break the ValueString and read the default values.
Regex.Matches(valuestring,#"(?<=-)(\d*)(?<=,)?");
The regular expression uses non-capturing groups to capture a number which is prefixed as by an optional "-" character and suffixed by an optional "," character.
Once the defaults are parsed into a List (assuming that the positions are in order and do not miss any values), we loop through the input string (which has been split based on delimiter), check if it is Empty, and if so, use the value from the Defaults (based on our assumption, it should have same index).
Update
Based on the comments, it looks like you other data in the original string, and hence the concerned sub-string has to be captured first.
We could update the Missing Number method as
static string MissingNumber(string Number)
{
string valuestring = "first-12,second-10,third-99,fourth-9,fifth-09";
var regexDefaultValues = Regex.Matches(valuestring,#"(?<=-)(\d*)(?<=,)?");
var defaults = regexDefaultValues.Cast<Match>().Select(x=>x.Value).ToList();
var regexNumberToParse = new Regex(#"(\d)*-(\d)*-(\d)*-(\d)*-(\d)*");
var capturedNumberFormat = regexNumberToParse.Match(Number).Value;
var newArray = capturedNumberFormat.Split('-').Select((x,index)=>string.IsNullOrEmpty(x)?defaults[index]:x);
var ValueWithDefaults = string.Join("-",newArray);
return regexNumberToParse.Replace(Number,ValueWithDefaults);
}
Demo Code

Parsing string with 3 hyphens C#

I have string COO70-123456789-12345-1. I need to parse based on the "-" not the length of the substrings and use the parsed values. I have tried using Regular expressions but having issues.Please suggest.
Also after I have split the values I need to use each values: string A = COO70, int B = 123456789, int C = 12345, short D = 1 . How do I get it in different variables A,B,C,D.
string[] results = UniqueId.Split('-');
string A = results[0];
string B = results[1];
string C = results[2];
int k_id = Convert.ToInt32(k_id);
string D = results[3];
short seq = Convert.ToInt16(seq);
string s = "COO70-123456789-12345-1";
string[] split = s.Split('-'); //=> {"COO70", "123456789", "12345", "1"}
Use indexOf
To find everything before the first hyphen use:
string original= "COO70-123456789-12345-1";
string toFirstHyphen=original.Substring(0,original.IndexOf("-"));
Or if you want every section use split like the above example.
You can verify whether the input is formatted as you want and then split to get the parts.
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string pattern = #"(?x)^(\w+-\w+-\w+-\w+)$";
Regex reg = new Regex(pattern);
string test = "word-6798-3401-001";
if((reg.Match(test).Success))
foreach (var x in test.Split(new char[] {'-'}))
Console.WriteLine(x);
}
}
So it sounds like you first want to split it, but then store it into your values.
I would do something like this:
var myString = "COO70-123456789-12345-1";
var stringSet = myString.Split("-"); // This returns an array of values.
Now we need to verify that we receive only 4 sub strings:
if (stringSet.Count != 4)
throw Exception e; // Throw a real exception, not this
From here we need to know what order our strings should be in and assign them:
var A = stringSet[0];
var B = stringSet[1];
var C = stringSet[2];
var D = stringSet[3];
While this should answer your question as posed, I would recommend you work with stringSet differently personally.

string.split based on nth position of comma in c#

I have string:
string string1 = "0,11,22,33,5500,2000,9800,10,10,10,10,10,10,10,10,10,10,";
Now I have to split this string from 4th position of comma. I need to get values 5500,2000,9800 separately.
How can I split my string like this?
You can use LINQ and Skip:
var array = string1.Split(',').Skip(4).ToArray();
If you want to limit the elements of array (just want to get the 3 values):
var array = string1.Split(',').Skip(4).Take(3).ToArray();
I assume you don't know LINQ, so rember to import namespaces in order to use LINQ extension methods (if not imported):
using System.Linq;
EDIT (see comments):
var splitted = string1.Split(',');
var firstArr = splitted.Take(4);
var secondArray = splitted.Skip(4).Take(3);
var thirdArray = splitted.Skip(7);
If you want to have them like a string:
var s1 = string.Join(",", firstArray);
var s2 = string.Join(",", secondArray);
var s3 = string.Join(",", thirdArray);
.Why don't you do it like this:
string string1 = "0,11,22,33,5500,2000,9800,10,10,10,10,10,10,10,10,10,10,";
string[] parts = string1.Split(',');
As the OP asked a follow up question here is his answer:
To join the parts do it like this:
string firstPart = string.Join(",",parts.Take(4));
string secondPart = string.Join(",",parts.Skip(4).Take(3));
string thirdPart= string.Join(",",parts.Skip(7));

How to split a string with '#' in C#

I tried to split a string wich contains these character #
domicilioSeparado = domicilio.Split(#"#".ToCharArray());
but every time the array contains just one member. I've tried a lot of combinations but anything seems to work, I also tried to replace the string with a blank space and it kinda works - the problem is that it remains a single string.
domicilio = domicilio.Replace(#"#", #" ");
How can I resolve this?
Complete code:
String[] domicilioSeparado;
String domicilio = dbRow["DOMICILIO"].ToString();
domicilioSeparado = domicilio.Split(#"#".ToCharArray());
if (Regex.IsMatch(domicilioSeparado.Last(), #"\d"))
{
String domicilioSinNum = "";
domicilioSinNum = domicilioSeparado[0];
custTable.Rows.Add(counter, dbRow["CUENTA"], nombre,
paterno, materno, domicilioSinNum, domicilioSeparado.Last(), tipoEntidad);
}
If you just want to split a string on a delimiter, in this instance '#', then you can use this:
domicilioSeparado = domicilio.Split("#");
That should give you what you want. Your second attempt simply replaces all the characters '#' in the string with ' ', which doesn't seem to be what you want. Can we see the string you're trying to split? That might help explain why it's not working.
EDIT:
Ok, here's how I think your code should look, give this a shot and let me know how it goes.
List<string> domicilioSeparado = new List<string>();
String domicilio = dbRow["DOMICILIO"].ToString();
domicilioSeparado = domicilio.Split("#");
if (Regex.IsMatch(domicilioSeparado.Last(), #"\d"))
{
String domicilioSinNum = "";
domicilioSinNum = domicilioSeparado[0];
custTable.Rows.Add(counter, dbRow["CUENTA"], nombre,
paterno, materno, domicilioSinNum, domicilioSeparado.Last(), tipoEntidad);
}
Try this:
string[] domicilioSeparado;
domicilioSeparado = domicilio.Split('#');
Some notes:
1 - It is ('#'), instead of ("#"); 2 - Replace does not split a string, it only replace that part, keeping as a single string.
In case you want an example that includes the printing of the whole array:
string domicilio = "abc#def#ghi";
string[] domicilioSeparado;
domicilioSeparado = domicilio.Split('#');
for (int i = 0; i < domicilioSeparado.Length; i++)
{
MessageBox.Show(domicilioSeparado[i]);
}
It will open a Message Box for each element within domicilioSeparado.

How to split a string and assign each word to a new variable?

I'm making a credit card processing form. The field in question is Name: (first and last).
What would some C# code look like that would take the text from a text box and split it, then assign each word (in this case first and last name) into two new strings?
E.g. txtName.Text = "John Doe"
After split
string fName = "John";
string LName = "Doe";
You can split the text on a character or string into a string array, and then pull the individual parts of the name out of the array. Like so:
string[] nameParts = txtName.Text.Split(' ');
string firstName = nameParts[0];
string lastName = nameParts[1];
But why not just have a separate text box for each part of the name? What if somebody puts their full name in the text box (i.e. you'd have three parts, not just two).
string[] names = txtName.Text.Split(' ');
string fName = names[0];
string LName = names[1];
it helps you to split a string in a part
string FullMobileNumber = "+92-342-1234567";
string[] mobile = FullMobileNumber.Split('-');
_txtCountryCodeMobile.Text = mobile[0];
_MobileCodeDropDown.SelectedValue = mobile[1];
_txtEmployeeMobileNumber.Text = mobile[2];
String.Split returns an array, so... just assign from the array.

Categories