gpt4 book ai didi

java - 将字符串转换为标题大小写

转载 作者:行者123 更新时间:2023-11-29 09:43:21 24 4
gpt4 key购买 nike

我是 Java 的初学者,试图编写一个程序将字符串转换为首字母大写。例如,如果 String s = "my name is milind",则输出应为 "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);
//}
}
}

最佳答案

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

  1. 把单词分开
  2. 将每个单词大写
  3. 把它们放在一起
  4. 打印出来

示例代码:

  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);
}

关于java - 将字符串转换为标题大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34949170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com