What am i doing wrong here? I want the users name to be shown in the output as propercase but I cant figure it out.
string proper = this.xTripNameTextBox.Text;
CultureInfo properCase = System.Threading.Thread.CurrentThread.CurrentCulture;
TextInfo currentInfo = properCase.TextInfo;
proper = currentInfo.ToTitleCase(proper);
this.xTripOutputLabel.Text = proper + Environment.NewLine + "The total gallons you would use: " + Output.ToString("0") + Environment.NewLine + "Total amount it will cost you: " + Coutput.ToString("C") + Environment.NewLine +" Your customer number is " + rnd1.Next(1, 1000).ToString();
I have tested the following on an all upper case word at it works:
string proper = "TEST STRING";
CultureInfo properCase = System.Threading.Thread.CurrentThread.CurrentCulture;
TextInfo currentInfo = properCase.TextInfo;
proper = currentInfo.ToTitleCase(currentInfo.ToLower(proper));
// proper = "Test String"
So - change the string to lower case before calling ToTitleCase.
The MSDN documentation does say that a string that is all upper case (such as an acronym) will not be converted and the sample code provided in the post corroborates this.
That's according to spec, quote from the doc: However, this method does not currently provide proper casing to convert a word that is entirely uppercase
http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx
Without testing I'd guess that you could do it by first making it LowerCase and then TitleCase.
Seems right, I am using
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text);
And it's working.
Try to force another culture info.
See Also
How to capitalize the first character of each word, or the first character of a whole string, with C#?
Related
I would like to find match
I prefer to "IndexOf" (not RegExp or something, becuase it is pretty simple codes).
I have a problem with strange character.
The situation is Given, I can not control it.
Let's see the screenshot, that is good enough.
It should make result "-1" but it makes not "-1" (0 in this case).
Thanks.
string myString1 = "abc";
string myString2 = "abc�";
MessageBox.Show(
"Result \n" +
myString1.IndexOf(myString2));
enter image description here
You should be using StringComparison.Ordinal
string myString1 = "abc";
string myString2 = "abc�";
MessageBox.Show("Result \n" + myString1.IndexOf(myString2, StringComparison.Ordinal));
It's just on of those weird "gotchas" that shows using culture information can sometimes really matter.
I am trying to remove the last 6 characters from item.Size because the data has a decimal place and 5 trailing 0s in the database.
sb.Append("<div>" + item.Size + " " + item.Units + " </div>");
ie. item.Size is displayed as 1.00000 and I need it to just be displayed as 1.
This is part of a StringBuilder, and as I'm new to coding, not even sure the right way to go about this.
sb.Append("<div>" + (int)item.Size + " " + item.Units + " </div>");
StringBuilder has the same formatting capabilities as String.Format when you use the AppendFormat method:
sb.AppendFormat("<div>{0:N0} {1} </div>", item.Size, item.Units);
The format string "N0" tells it to format the number with 0 decimal points. That assumes the item.Size is stored as a numerical type. If not, simply remove the part of the string you don't want:
sb.AppendFormat("<div>{0} {1}</div>", item.Size.Split('.')[0], item.Units);
Here I've used Split, assuming that the value is actually something like what you've shown in your example.
Better you use int.TryParse(or Int32.TryParse) method. because if item.Size is not convertible to int, then it wont give you any exception. you can use int or long according to your choice. So you can handle this in your code according to the if/else condition.
Sample Code:
int size;
string str = "";
if(int.TryParse(str, out size) == true)
{
}
else
{
}
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;
Is there any difference between the use of {0} and + as they both are doing the same work of printing the length on the screen:
Console.WriteLine("Length={0}", length);
Console.WriteLine("Length=" + length);
In your trivial example there's no difference. But there are very good reasons to prefer the formatted ({0}) option: it makes localization of international software much, much easier, and it makes editing your existing strings by third parties much easier.
Imagine for example you're writing a compiler that produces this error message:
"Cannot implicitly convert type 'int' to 'short'"
Do you really want to write the code
Console.WriteLine("Cannot implicitly convert type '" + sourceType + "' to '" + targetType + "'");
? Good heavens no. You want to put this string into a resource:
"Cannot implicitly convert type '{0}' to '{1}'"
and then write
Console.WriteLine(FormatError(Resources.NoImplicitConversion, sourceType, targetType));
Because then you have the freedom to decide that you want to change that to:
"Cannot implicitly convert from an expression of type '{0}' to the type '{1}'"
Or
"Conversion to '{1}' is not legal with a source expression of type '{0}'"
These choices can be made later, by English majors, without requiring changes to the code.
You can also translate those resources into other languages, again without changing the code.
Start always using formatting strings now; when you need to write localizable software that uses string resources properly, you'll already be in the habit.
The second line will create a string and print the string out.
The first line will use composite formatting, like string.Format.
Here are some good reasons to use composite formatting.
There is a difference.
ex:
Console.WriteLine("the length is {0} which is the length", length);
Console.WriteLine("the length is "+length+" which is the length");
+ concatenates two strings, {0} is a placeholder for a string to be inserted.
{n} is a placeholder which can be used with multiple options. where n is a number
In your example it would make a difference and the end result would be same that is concatenation of two string. However in something like
var firstName = "babba";
var lastName ="abba";
var dataOfBirth = new Date();
Console
.Write(" Person First Name : {0} | Last Name {1} }| Last Login : {2:d/M/yyyy HH:mm:ss}",
firstName,
secondName,
dateOfBirth);
it provides a easy to read interface with easy formatting
{n} where n >= 0 allows you to substitute values in order of occurrence in the string.
string demo = "demo", example = "example";
Console.WriteLine("This is a {0} string used as an {1}", demo, example);
+ allows you to concatenate two or more strings together.
Console.WriteLine("This is a " + demo + " string used as an " + example);
I have read all similar questions and acted accordingly. But still can't figure out what's wrong with my code.
This is my code, super simple. (I know this isn't valid XML. It's just for the example).
string replacement = "TimeSheetsReplaced";
string word = "TimeSheets";
string result = "<?xml version=\"1.0\" encoding=\"utf-16\"?><DisplayName>Timesheets</DisplayName>";
result = result.Replace("<DisplayName>" + word + "</DisplayName>", "<DisplayName>" + replacement + "</DisplayName>");
The result string remains unplaced. What am I doing wrong??
TimeSheets != Timesheets
Casing does not match
It's because your string contains Timesheets, but you're lokoing for TimeSheets (with a capital S).
In your word TimeSheets has big S, in string small s