将字符串转换为标题案例 [英] Convert String into Title Case

查看:128
本文介绍了将字符串转换为标题案例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的初学者,试图编写一个程序来将字符串转换为标题大小写。例如,如果 String s =my name is milind,那么输出应为我的名字是Milind

I am a beginner in Java trying to write a program to convert strings into title case. For example, if String s = "my name is milind", then the output should be "My Name Is Milind".

import java.util.*;
class TitleCase
{
public static void main(String args[])
{
    Scanner in = new Scanner(System.in);
    System.out.println("ent");

    String s=in.nextLine();
    String str ="";        
    char a ;

    for(int i =0;i<s.length()-1;i++)
    {
        a = s.charAt(i);
        if(a==' ')
        {
            str = str+(Character.toUpperCase(s.charAt(i+1)));
        }
        else
        {
            str =str+(Character.toLowerCase(a));
        }

    }

    //for(int i =0; i<s.length();i++)
    //{
        System.out.println(str);
    //}
}
}


推荐答案

您正在尝试将输入的每个单词都大写。
所以你必须执行以下步骤:

You are trying to capitalize every word of the input. So you have to do following steps:


  1. 将单词分开

  2. capitalize每个单词

  3. 把它们放在一起

  4. 打印出来

  1. get the words separated
  2. capitalize each word
  3. put it all together
  4. print it out

示例代码:

  public static void main(String args[]){
     Scanner in = new Scanner(System.in);
     System.out.println("ent");

     String s=in.nextLine();

     //now your input string is storred inside s.
     //next we have to separate the words.
     //here i am using the split method (split on each space);
     String[] words = s.split(" ");

     //next step is to do the capitalizing for each word
     //so use a loop to itarate through the array
     for(int i = 0; i< words.length; i++){
        //we will save the capitalized word in the same place again
        //first, geht the character on first position 
        //(words[i].charAt(0))
        //next, convert it to upercase (Character.toUppercase())
        //then add the rest of the word (words[i].substring(1))
        //and store the output back in the array (words[i] = ...)
        words[i] = Character.toUpperCase(words[i].charAt(0)) + 
                  [i].substring(1);
     }

    //now we have to make a string out of the array, for that we have to 
    // seprate the words with a space again
    //you can do this in the same loop, when you are capitalizing the 
    // words!
    String out = "";
    for(int i = 0; i<words.length; i++){
       //append each word to out 
       //and append a space after each word
       out += words[i] + " ";
    }

    //print the result
    System.out.println(out);
 }

这篇关于将字符串转换为标题案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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