a C# program, as you see , var month is defined as int, someone said without .tostring() is better, it should remove redundant call, now it is:str= "0" + Month;
but i think it's not good .which one is better? why? thanks!(ps:my first question in stackoverflow)
string strM = string.Empty;
if ( Month < 10 )
strM = "0" + Month.ToString ( );
//strM = "0" + Month; which is better?
Use string format instead:
string strM = string.Format("{0:00}", Month);
Test:
Month: 1 => strM: "01"
Month: 12 => strM: "12"
For more string format tips check this.
The best way is to use .tostring, but not as shown.
using System;
class example {
static void Main(string[] args) {
int Month =5;
Console.WriteLine(Month.ToString("00"));
}
}
http://ideone.com/LCwca
Outputs: 05
As for your question other part, there is no difference, only clarity (style) of the code. Which to use it up to you. If you want to make an accent on that Month is not a string then you can add .ToString(). If this is obvious, like with if ( Month < 10 ), so you can see one line above comparison with int, hence Month is definetely not a string you can omit .ToString() call since it will be done automatically.
Related
I'm trying to create a STRING in JSON format. However, one of the fields (from my editing/removing ALL spaces) now leaves a line like "START":"13/08/1410:30:00". However, I want to add a space between the date and time? I have tried using the ToCharArray() method to split the string, but I am at a loss as to how to add a space between the DATE and TIME part of the string?
For Example, i am trying to get: "START":"13/08/14 10:30:00" but instead am getting
"START":"13/08/1410:30:00"
Please note. The length of the string before the space requirement will always be 17 characters long. I am using VS 2010 for NETMF (Fez Panda II)
If the split position is always 17, then simply:
string t = s.Substring(0, 17) + " " + s.Substring(17);
Obviously you will have to sort the numbers out, but thats the general idea.
String.Format("{0} {1}", dateString.Substring(0, 17), dateString.Substring(17, dateString.Length - 17);
Or you can use the StringBuilder class:
var finalString = new StringBuilder();
for (var i = 0; i < dateString.Length; i++){
if (i == 17)
finalString.Add(" ");
else
finalString.Add(dateString.ToCharArray()[i]);
}
return finalString.ToString();
If the date time format always the same you can use string.Insert method
var output = #"""START"":""13/08/1410:30:00""".Insert(17, " ");
Strings in .Net are immutable: you can never change them. However, you can easily create a new string.
var date_time = dateString + " " + timeString;
I am generating 35 strings which have the names ar15220110910, khwm20110910 and so on.
The string contains the name of the Id (ar152,KHWM), and the date (20110910). I want to extract the Id, date from the string and store it in a textfile called StatSummary.
My code statement is something like this
for( int 1= 0;i< filestoextract.count;1++)
{
// The filestoextract contains 35 strings
string extractname = filestoextract(i).ToString();
statSummary.writeline( extractname.substring(0,5) + "" +
extractname.substring(5,4) + "" + extractname.substring(9,2) + "" +
extractname.substring(11,2));
}
When the station has Id containing 5 letters, then this code executes correctly but when the station Id is KHWM or any other 4 letter name then the insertion is all messed up. I am running this inside a loop. So I have tried keeping the code as dynamic as possible. Could anyone help me to find a way without hardcoding it. For instance accessing the last 8 elements to get the date??? I have searched but am not able to find a way to do that.
For the last 8 digits, it's just:
extractname.Substring(extractname.Length-8)
oh, I'm sorry, and so for your code could be:
int l = extractname.Length;
statSummary.WriteLine(extractname.substring(0,l-8) + "" +
extractname.Substring(l-8,4) + "" + extractname.Substring(l-4,2) + "" +
extractname.Substring(l-2,2));
As your ID length isn't consistent, it would probably be a better option to extract the date (which is always going to be 8 chars) and then treat the remainder as your ID e.g.
UPDATED - more robust by actually calculating the length of the date based on the format. Also validates against the format to make sure you have parsed the data correctly.
var dateFormat = "yyyyMMdd"; // this could be pulled from app.config or some other config source
foreach (var file in filestoextract)
{
var dateStr = file.Substring(file.Length-dateFormat.Length);
if (ValidateDate(dateStr, dateFormat))
{
var id = file.Substring(0, file.Length - (dateFormat.Length+1));
// do something with data
}
else
{
// handle invalid filename
}
}
public bool ValidateDate(stirng date, string date_format)
{
try
{
DateTime.ParseExact(date, date_format, DateTimeFormatInfo.InvariantInfo);
}
catch
{
return false;
}
return true;
}
You could use a Regex :
match = Regex.Match ("khwm20110910","(?<code>.*)(?<date>.{6})" );
Console.WriteLine (match.Groups["code"] );
Console.WriteLine (match.Groups["date"] );
To explain the regex pattern (?<code>.*)(?<date>.{6}) the brackets groups creates a group for each pattern. ?<code> names the group so you can reference it easily.
The date group takes the last six characters of the string. . says take any character and {6} says do that six times.
The code group takes all the remaining characters. * says take as many characters as possible.
for each(string part in stringList)
{
int length = part.Length;
int start = length - 8;
string dateString = part.Substring(start, 8);
}
That should solve the variable length to get the date. The rest of the pull is most likely dependent on a pattern (suggested) or the length of string (when x then the call is 4 in length, etc)
If you ID isn't always the same amount of letters you should seperate the ID and the Date using ',' or somthing then you use this:
for( int 1= 0;i< filestoextract.count;1++)
{
string extractname = filestoextract[i].ToString();
string ID = extractname.substring(0, extractname.IndexOf(','));
string Date = extractname.substring(extractname.IndexOf(','));
Console.WriteLine(ID + Date);
}
i am strugling with an exercise. I am a beginer and dont know where to start. I am asked to create a console program that if you give it a number between 1 and 12 it must give you the corresponding month name and if you give it the name of the month it should give you the number of the month. Please help with the code. It should be done using an ARRAY. Thank you.
Depends on what you're learning, I guess... they may just be demonstrating a switch(intMonth) type thing, so:
switch(intMonth)
{
case 1:
return "January";
break;
case 2:
return "February";
break;
....
}
Or as mentioned, make use of DateTime...
There's many many ways to do it... I guess you need to select the right way... most efficient way... so, depends on your assignment.
Good luck.
Hopefully you will learn something from this code, because if it gets copied to a USB stick and givent to the teacher without even taking alook to it, I will be very mad, come to your home and do a mess! :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int iMonth = -1;
// loop until iMonth is 0
while (iMonth != 0)
{
Console.WriteLine("Please insert a number from 1 to 12 and press enter. Enter 0 to exit.");
string sMonth = Console.ReadLine();
// try to get a number from the string
if (!int.TryParse(sMonth, out iMonth))
{
Console.WriteLine("You did not enter a number.");
iMonth = -1; // so we continue the loop
continue;
}
// exit the program
if (iMonth == 0) break;
// not a month
if (iMonth < 1 || iMonth > 12) {
Console.WriteLine("The number must be from 1 to 12.");
continue;
}
// get the name of the month in the language of the OS
string monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(iMonth);
Console.WriteLine("The name of the month is " + monthName);
}
}
}
}
If your teacher expects a custom provided name then you can use the switch statement in the last part:
switch (iMonth)
{
case 1:
Console.WriteLine("January");
break;
case 2:
Console.WriteLine("February");
break;
// add more
}
If he expects an array exercise then you can declare an array with all the strings and use that:
string[] monthNames = new string[] {
"January",
"February",
// add more
};
and use this to get the name:
Console.WriteLine(monthNames[iMonth]);
Do like that :
String to Int Month
Code :
Datetime.Parse(Monvalue + "/1/2011").ToString("MM")
Like :
Datetime.Parse("January/1/2011").ToString("MM")
Retrun :
01
Int to String Month
Code :
Datetime.Parse( Monvalue +"/9/2011").ToString("MMMMM")
Like :
Datetime.Parse("1/9/2011").ToString("MMMMM")
Retrun :
"January"
Before this you should handle wrong cases.I hope its help to you
As Ernest suggested, take a look at the DateTimeFormat property within System.Globalization.CultureInfo. What you're looking for is a method called GetMonthName(). The number passed into GetMonthName() is a numerical representation of that month.
static void Main(string[] args)
{
Console.WriteLine("Give me an integer between 1 and 12, and I will give you the month");
int monthInteger = int.Parse(Console.ReadLine());
DateTime newDate = new DateTime(DateTime.Now.Year, monthInteger, 1);
Console.WriteLine("The month is: " + newDate.ToString("MMMM"));
Console.WriteLine();
Console.WriteLine("Give me a month name (ex: January), and I will give you the month integer");
string monthName = Console.ReadLine();
monthInteger = DateTime.ParseExact(monthName + " 1, " + DateTime.Now.Year, "MMMM d, yyyy", System.Globalization.CultureInfo.InvariantCulture).Month;
Console.WriteLine("The month integer is " + monthInteger);
Console.ReadLine();
}
The task of translating between numbers and names is quite trivial, so how you do it depends on what kind of language elements you are currently learning.
You can divide the problem into several sub-task, like determining if the input is a number of a name, picking the right conversion based on that, and the two different ways of doing the conversion. Each sub-task can be solved in several different ways.
To examine the input you could compare it to month names, and if none of them matches assume that it's a number, or you could use Int32.TryParse to try to parse the input as a number, and if that fails assume that it's a month name.
The most basic way of doing the conversion would be a lot of if statements. You could also use a switch, use an array of month names, or use dictionaries for the separate lookups.
private string[] months = { "Jan", "Feb", "Mar", "Apr" };
public string GetMonth(int x)
{
if(x > 0 && x < months.Length)
return months[x];
else
return "";
}
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.
I have a string like 20090101 and I want to compare it with ????01??.
if (input == "----01--") { .... }
How can I compare the 5th and 6th characters with "01"?
Update: After seeing your comment I think you should parse the string as a DateTime:
string s = "20090101";
DateTime dateTime;
if (DateTime.TryParseExact(s, "yyyyMMdd", null, DateTimeStyles.None, out dateTime))
{
if (dateTime.Month == 1)
{
// OK.
}
}
else
{
// Error: Not a valid date.
}
I think this may be what you want:
if (input.Substring(4, 2) == "01")
{
// do something
}
This will get a two character substring of input (starting at character 5) and compare it to "01".
you should create a regex expression. to check if the 4th and 5th byte is 01, you can write
var r = new Regex("^.{4}01$");
if(r.Match(str) ...) ...
MSDN has a great article on comparing strings, but you may want to refer to the String documentation for specific help, most notably: String.Compare, String.CompareTo, String.IndexOf, and String.Substring.
As Bauer said you can use String functions, also you can convert string to Char Array and work with it char by char