在“-”(indexOf)之后大写传递

时间:2018-12-11 12:50:13

标签: java

在练习中,我必须将破折号后的字符更改为大写。

例如-> jean-louis becomes Jean-Louis

我知道第一个字符要大写,但是破折号后我不明白。

String name= null;                      // enter the name
String letterSlice = null;              // slice the first letter
String letterSliceUpper = null;         // first letter in uppercase
String remainingLetters = null;         // remaining letters
int dashIndex = 0;                      // dash


System.out.print("Enter your name please : ");
name = input.next();

letterSlice = name.substring(0,1);
letterSliceUpper = letterSlice.toUpperCase();
remainingLetters = name.substring(1);

dashIndex = name.indexOf("-");

if(remainingLetters.indexOf("-") != -1 ){

}

System.out.print(letterSliceUpper.concat(remainingLetters));

感谢您的帮助。

5 个答案:

答案 0 :(得分:4)

我将从构造一个StringBuilder(可变字符集合)开始,将首字母大写,然后搜索-个字符。大写-之后的每个字符。喜欢,

String name = "jean-louis-patrice";
StringBuilder sb = new StringBuilder(name);
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
int p = 0;
while ((p = sb.indexOf("-", p + 1)) != -1) {
    if (p + 1 < sb.length()) {
        sb.setCharAt(p + 1, Character.toUpperCase(sb.charAt(p + 1)));
    }
}
System.out.println(sb);

输出

Jean-Louis-Patrice

答案 1 :(得分:2)

这是使用RegEx的另一种解决方案

String str = "jean-louis-patrice";

Pattern pattern = Pattern.compile("(^.|-.)");
Matcher matcher = pattern.matcher(str);

StringBuffer result = new StringBuffer();
while (matcher.find()) {
       matcher.appendReplacement(result, matcher.group().toUpperCase());
}

matcher.appendTail(result);

System.out.println(result.toString());

答案 2 :(得分:0)

使用StringBuilder而不是创建很多String(内存效率高)。请尝试以下:

System.out.print("Enter your name please : ");
name = input.next();
StringBuilder result = new StringBuilder(name.length());
String words[] = name.split("-"); 
for (int i = 0; i < words.length; i++){  
 result.append(Character.toUpperCase(words[i].charAt(0))).append(words[i].substring(1)).append("-");  
}
System.out.println(result);

答案 3 :(得分:0)

您需要保留-的索引才能替换以下字符,例如

int indexOfDash = name.indexOf('-');

此外,我会将String转换为Char数组。它更容易操作。像

char[] charArray = name.toCharArray();
charArray[0] = Character.toUpperCase(charArray[0]);
if (indexOfDash != -1) {
    charArray[indexOfDash + 1] = Character.toUpperCase(charArray[indexOfDash + 1]);
}
String newName = String.valueOf(charArray);
System.out.println(newName);

答案 4 :(得分:0)

    public class MyClass 
    {
        public static void main(String args[]) {
            String s = "word-word";
            String[] list = s.split("-");

            String res = "";
            for(int i = 0; i < list.length; i++)
            {
                String _temp = list[i].substring(0, 1).toUpperCase();
                _temp += list[i].substring(1);
                res += _temp;

                if( i != list.length -1 )
                {
                    res += "-";
                }
            }

            System.out.println(res);    
        }
    }