I have a string "10/15/2010"
I want to split this string into 10, 15, 2010 using c#, in VS 2010. i am not sure how to do this. If someone can tell me what function to use, it would be awesome.
Thank you so much!!
You probably want to call
DateTime date = DateTime.Parse("10/15/2010", CultureInfo.InvariantCulture);
string str = "10/15/2010";
string[] parts = str.split('/');
You now have string array parts that holds parts of that initial string.
Take a look at String.Split().
string date = "10/15/2010";
string[] dateParts = date.Split('/');
Or do like a saw in a recent program (in Fortran which I am translating to C# below) ..
string[] parts = "10/15/2010".Split('/');
if( parts[0] == "01" ) month = 1;
if( parts[0] == "02" ) month = 2;
if( parts[0] == "03" ) month = 3;
if( parts[0] == "04" ) month = 4;
...
you get the idea. It kills me when people code it something crazy instead of calling a built in function to do the same thing.
( please don't flag me down, this is just a joke, not a real answer to the question )
Depending on how you plan to consume the information, you can choose strings, like has already been suggested, or parse it into a date then pull out the pieces.
DateTime date = DateTime.Parse("10/15/2010");
int y = date.year;
int m = date.Month;
int d = date.Day;
"10/15/2010".Split('/')
Assuming you wanted the "split" elements to be strings as well:
string date = "10/15/2010";
string[] split = date.Split('/');
var date = "10/15/2010";
var split = date.Split('/')
Simple:
string[] pieces = "10/15/2010".Split ('/');
Using String.Split.
Related
I need to parse a string in order to get a valid time (hours and secondes).
Here is an example of the source data :
7:00-7:30
7:30-8:00
8:00-8:30
...
19:30-20:00
I only need the first time value.
So for the firt line i need to get "7:00".
Moreover the hour part can have one or two digit (7:00 / 20:00).
Any idea to get that ?
Do you want a Timespan?
var str = "7:00-7:30";
var time = TimeSpan.Parse(str.Split('-')[0]);
if not, you can use
var hours = str.Split('-')[0].Split(':')[0];
var minutes = str.Split('-')[0].Split(':')[1];
the data you're looking for is unchanging from line to line, so a regex isn't really necessary here.
You don't need a regex. Just split it on the - which will return an array of which the first element at 0 index will contain what you want.
string date = "7:00-7:30"; bool val = date.IndexOf("-") > -1;
var splitter = val ? "-" : ":";
var arr = date.Split(splitter);
var firstpart = val ? arr[0] : arr[0] + ':' + arr[1];
You can use a regex of the form
^(?:1?[0-9]|2[0-3]):[0-6][0-9]
For example : http://regex101.com/r/fM3kL7/1
var re = /^(?:1?[0-9]|2[0-3]):[0-6][0-9]/gm;
var str = '7:00-7:30\n7:30-8:00\n8:00-8:30\n...\n19:30-20:00';
var res = str.match(re);
Will give an output as
7:00,7:30,8:00,19:30
I have a string of the days of the week. I parse it in C# and store each day in a separate variable. For example:
string weekdayName = "Mon,Tue,Wed,Thu,Fri,Sat,Sun";
And the I split them using ',' as a delimiter:
var weekDayName = weekDay.Split(',');
var firstDay = weekDayName[0];
var secondDay = weekDayName[1];
var thirdDay = weekDayName[2];
var fourthDay = weekDayName[3];
var fifthDay = weekDayName[4];
var sixDay = weekDayName[5];
var seventhDay = weekDayName[6];
Everything works. However, the string dynamically changes. A user assigns the days of the week. For example a string weekDayName could only contain "Mon,Tue". But the problem i'm running into is if not all the position contains value it will fail.
Index was outside the bounds of the array.
I have tried:
if (weekDayName[5].Length >0)
{
var sixDay = weekDayName[5];
}
But it still fails...
How can I check and grab the value of the existing data, if some of the position are missing I just ignore them?
What I'm trying to achieve is:
DateTime currentDay = new DateTime();
currentDay = DateTime.Now;
if (currentDay.ToString("ddd") == firstDay || currentDay.ToString("ddd") == seconday)
{
// I will check the currentDay against every day of the week
//do something
}
Your index out of range is not coming from where you think. I am of course assuming this since you tried to check length on an element that was never set if the user enters Mon,Tue.
var enteredDays = weekDay.Split(',');
for(var i = 0; i < enteredDays.Length; i++)
{
var day = enteredDays[i];
if(i == 0)
first = day;
else if(i == 1)
second = day;
... etc....
}
Now you can check String.IsNullOrEmpty(..yourDay..) when you need to use the values you pulled from the array. You can't use .Length on them because they are null and will blow up unless you default them all to string.Empty.
There must be some smarter way of doing this, but since i do not know where the string originates from, it is hard for me to make a better solution.
However, given the current requirements, you could do something like:
string weekdayName = "Mon,Tue,Wed,Thu,Fri,Sat,Sun";
List<String> weekDaysList = weekdayName.Split(',').ToList();
foreach (var weekDay in weekDaysList.Take(2))
{
if (weekDay == DateTime.Now.ToString("ddd"))
{
// do something
break;
}
}
If you're willing to try Linq (which is a language feature of C# 3.5 and higher, just include the System.Linq namespace) you could do it like this:
string[] names = weekdayName
.Split(',')
.Select(s => s.Trim())
.Where(s => s.Length > 0)
.ToArray();
The names array now contains all non-empty day names, without any leading or trailing spaces.
Wow that's a lot of code for a simple check, As mentioned by other members you can use LINQ to merge all validations in single query something like :
string weekdayName = "Mon,Tue,Wed,Thu,Fri,Sat,Sun";
var wc = weekdayName.Split(',');
if (wc.Any(str => str.Contains(DateTime.Today.DayOfWeek.ToString().Substring(0,3))))
{
}
Try this and let me know if you have any concerns.
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);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
.NET String.Format() to add commas in thousands place for a number
I am trying to add commas to a number for the presentation layer and need to cast and then split the number on every third character in order to join on a ','.
So if i have a string like this
546546555
desired output:
546,546,555
Other times, the number could be longer or shorter:
254654
desired output:
254,654
Is it possible to split in this manner then join with a comma?
tahnks!
EDIT:
Hi Everyone,
Thanks very much for your help.
To add to this post I also found a way to do this in SQL:
SUBSTRING(CONVERT(varchar, CAST(NumItems AS money), 1), 0, LEN(CONVERT(varchar, CAST(NumDocs AS money), 1)) - 2) as [NumDocs]
Rather than splitting the string manually, you should convert it to a number (or leave it as a number), and call the ToString method with the appropriate formatting:
Example
int value = 546546555;
string displayValue = value.ToString("#,#");
See this MSDN page for different format values:
C - Currency format
D - Decimal format
E - Scientific format
F - Fixed point format
G - General format
N - Number format
P - Percent format
R - Round trip format
X - Hexadecimal format
You should do this by converting your string to an integer, using Parse or ideally TryParse and use string formatting to display it:
var str = "546546555";
var formatted = String.Empty;
int value = 0;
if(int.TryParse(str,out value))
{
formatted = value.ToString("#,#");
}
Live example: http://rextester.com/FHO11833
Assuming you aren't only trying to output numbers, here's a quick function that I believe would do what you are after:
string splitter(string tosplit, int num, string splitstring)
{
string output = "";
for (int i = 0; i < tosplit.Length; i += num)
if (i + num < tosplit.Length)
output += tosplit.Substring(i, num) + ",";
else
output += tosplit.Substring(i);
return output;
}
Here, the output of splitter("546546555", 3, ",") would be 546,546,555
This would not be ideal for numbers though, as the other answers would cover this case perfectly.
Not very good code, but it works.
public static string GetString(string val, int number)
{
List<string> res = new List<string>();
res.Add("");
int counter = 0, i = 0;
while (i < val.Length)
{
while (res[counter].Length < number && i < val.Length)
{
res[counter] += val[i];
i++;
}
res.Add("");
counter++;
}
return string.Join(",", res.Where(r => !string.IsNullOrEmpty(r)));
}
val - your input string
number - number of characters you want to split, equals to 3 in your case
Gene S and Dan seem to have the answer IMHO. The nice thing about using the built in formatting is that you can write localizable code. For example, the "," is the numeric group separator in the US, but the "." is used in Spain.
var val = 12345678;
CultureInfo c = CultureInfo.CurrentCulture;
Application.CurrentCulture = new CultureInfo("EN-us");
var s = String.Format("{0:#,#}", val);
Application.CurrentCulture = new CultureInfo("ES-es");
var i = String.Format("{0:#,#}", val);
Application.CurrentCulture = c;
How can I split a string such as "Mar10" into "Mar" and "10" in c#? The format of the string will always be letters then numbers so I can use the first instance of a number as an indicator for where to split the string.
You could do this:
var match = Regex.Match(yourString, "(\w+)(\d+)");
var month = match.Groups[0].Value;
var day = int.Parse(match.Groups[1].Value);
You are not saying it directly, but from your example it seems are you just trying to parse a date.
If that's true, how about this solution:
DateTime date;
if(DateTime.TryParseExact("Mar10", "MMMdd", new CultureInfo("en-US"), DateTimeStyles.None, out date))
{
Console.WriteLine(date.Month);
Console.WriteLine(date.Day);
}
var match = Regex.Match(yourString, "([|A-Z|a-z| ]*)([\d]*)");
var month = match.Groups[1].Value;
var day = int.Parse(match.Groups[2].Value);
I tried Konrad's answer above, but it didn't quite work when I entered it into RegexPlanet. Also the Groups[0] returns the whole string Mar10. You want to start with Groups[1], which should return Mar and Groups[2] should return 10.
char[] array = "Mar10".ToCharArray();
int index = 0;
for(int i=0;i<array.Length;i++)
{
if (Char.IsNumber(array[i]){
index = i;
break;
}
}
Index will indicate split position.