将文本框中每个单词的第一个字母大写 [英] Capitalize fiirst letter of each word in textbox

查看:127
本文介绍了将文本框中每个单词的第一个字母大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在尝试修改文本框中的文本,这样如果我输入''husain sabir'',它就会变成''Husain Sabir''。

这是我试过的代码:

Hi,
I am trying to modify the text in a textbox such that if I enter ''husain sabir'',it should become ''Husain Sabir''.
This is the code i tried :

public static string CapitalizeFirstLetters(string sValue)
        {
            char[] array = sValue.ToCharArray();
            // handle the first letter in the string
            if (array.Length >= 1)
            {
                if (char.IsLower(array[0]))
                {
                    array[0] = char.ToUpper(array[0]);
                }
            }

            // scan through the letters, checking for spaces
            for (int i = 1; i < array.Length; i++)
            {
                if (array[i - 1] == ' ')
                {
                    if (char.IsLower(array[i]))
                    {
                        array[i] = char.ToUpper(array[i]);
                    }
                }
            }

            return new string(array);
        }





但是它没有用。有人可以帮帮我吗?



But its not working.Can someone please help me out?

推荐答案

尝试 http://www.dotnetperls.com/uppercase-first-letter [ ^ ]。



如果您想使用扩展方法,请尝试 http://www.codemeit.com/code-collection/c-to-upper-case-first-letter-of-a-string.html [ ^ ] 。
Try http://www.dotnetperls.com/uppercase-first-letter[^].

If you want to use extension methods, try http://www.codemeit.com/code-collection/c-to-upper-case-first-letter-of-a-string.html[^].


它的代码为你创造了问题。



你这样检查if(array [i - 1] = ='''')



和像这个数组一样分配[i]



its this code creating problems for you.

You are checking like this if (array[i - 1] == '' '')

and assigning like this array[i]

for (int i = 1; i < array.Length; i++)
{
  if (array[i] == ' ')
  {
    if (char.IsLower(array[i+1]))
     {
        array[i+1] = char.ToUpper(array[i+1]); // space is identified at Index i so next i+1 has to converted to Upper!!
      }
    }
}


这是一个示例方法

Here is a sample approach
string Sampleinput = "husain sabir";
       string Output = "";
       string[] inputWords = Sampleinput.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

       foreach (string word in inputWords)
       {
           char[] a = word.ToCharArray();
           a[0] = char.ToUpper(a[0]);
           Output += new string(a) + " ";
       }
       Console.WriteLine(Output);


这篇关于将文本框中每个单词的第一个字母大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆