Capitalizing the first character of each word in a string (i.e. “the final countdown” → “The Final Countdown”).
C# has a built-in function for this. Its called ‘toTitleCase’, hidden deep within the System.Globalization namespace.
So how do you use it?
using System.Globalization; ... // Get the instance of the TextInfo class to use to (no constructor), comes from the current thread TextInfo info = (System.Threading.Thread.CurrentThread.CurrentCulture).TextInfo; string sample = "hello world"; // Print to console the title case // Outputs: Hello World Console.WriteLine(info.ToTitleCase(sample));
The ‘ToTitleCase’ function returns an instance of a string which will have all of the first characters in words changed to upper case, and leaves the rest of the text as is. This means that if a word is in all capital letters it will remain that way. A simple work around for this is to call the string object’s ‘ToLower’ function before we send the string into the ‘ToTitleCase’ function.
using System.Globalization; ... // Get the instance of the TextInfo class to use to (no constructor), comes from the current thread TextInfo info = (System.Threading.Thread.CurrentThread.CurrentCulture).TextInfo; string sample = "HELLO world"; // Print to console the title case // Emits: HELLO World Console.WriteLine(info.ToTitleCase(sample)); // Pre-lowercase everything // Emits: Hello World Console.WriteLine(info.ToTitleCase(sample.ToLower()));
The PHP version of this function is a fair bit easier to get to. PHP’s function is called ‘ucwords’. However, similar to the C# version you should always have the string sent in in lower case if you want it to only make the first character of each word upper case (it only changes the first character and doesn’t touch the others).
// Outputs: The Final Countdown echo ucwords('the final countdown');
Posted in programming
I was implementing an image resizer and I kept running into a problem where I kept getting error messages saying that the image file was in use even after I disposed of the object in memory (the last step was to remove the unresized image).
Calling object.Dispose() is just a suggestion to say “whenever you want, we don’t need this in memory anymore”. However, because it doesn’t get rid of it immediately, meaning that it is still being referenced which means that the file won’t be able to be deleted immediately.
In order to get around this, you need to call the garbage collector yourself to force the application to get rid of the object from memory.
string dest = @"C:\"; FileInfo imageFile = new FileInfo(file); Image image = ResizeImage(Image.FromFile(file),size); // Save the file to the file system SaveAsJpeg(image, dest + imageFile.Name, 100); // We don't need the image in memory any more (suggest it to be deleted) image.Dispose(); // Call the garbage collector GC.Collect(); GC.WaitForPendingFinalizers(); // Delete the old file imageFile.Delete();
Posted in php