I have a code to capitalize the first letter of every words except for one letter words. The problem I have is if the last word of that string is one letter, it gives a index out of range exception. Which makes sense because the code array[i + 1]
doesn't exist for the last letter.
static string UppercaseWords(string value)
{
char[] array = value.ToLower().ToCharArray();
// Handle the first letter in the string.
array[0] = char.ToUpper(array[0]);
// Scan through the letters, checking for spaces.
// ... Uppercase the lowercase letters following spaces.
for (int i = 1; i < array.Length; i++)
{
if (array[i - 1] == ' ' && array[i + 1] != ' ')
{
array[i] = char.ToUpper(array[i]);
}
}
return new string(array);
}
I'm just looking for something to get around that exception, or another way to do this. Thank you.
您可以改善条件,这样就不会要求第(i + 1)个索引。
if (array[i - 1] == ' ' && i + 1 < array.Length && array[i + 1] != ' ')
You could extract all the words (string parts separated by a white space) and convert to uppercase the first letter of the string part when the part length is > 1
:
string input = "this is a sample, string with: some => 1 letter words ! a";
StringBuilder sb = new StringBuilder(input.Length * 2);
foreach (string word in input.Split())
{
if (word.Length > 1) {
sb.Append(char.ToUpper(word[0]));
sb.Append(word.Substring(1));
}
else {
sb.Append(word);
}
sb.Append((char)32);
}
Console.WriteLine(sb);
Prints:
This Is a Sample, String With: Some => 1 Letter Words ! a
Suggestion:
I would do an extension class for your string handling :
public static class StringExtensions
{
public static string AllWordsInStringToUpperCase(this string value)
{
return string.Join(' ', value.Split(' ').Select(s => s.FirstCharToUpperCase()));
}
public static string FirstCharToUpperCase(this string word)
{
if (word.Length == 1)
return word;
return word.First().ToString().ToUpper() + word.Substring(1);
}
}
Than use it like this for en example in an Console application:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("fuu a bar".AllWordsInStringToUpperCase());
}
}
Output: Fuu a Bar
By that you can write some test so you know you get the behavior you want.
Peace!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.