如何将指定位置的字符转成大写?

路丶那么遥远
  • 160
上海市

需要查找到空格, 将空格后的一个字符转成大写

// 如何转成 "User Password" ?
String str = "user password";

网站找的方法自己改良了下, 感觉有些麻烦, 有没有更优的方案?

private static String getEnglish(String originalKey) {
    StringBuilder result = new StringBuilder();
    String[] arr = originalKey.split(" ");
    for (String item : arr) {
        result.append(item.substring(0, 1).toUpperCase()).append(item.substring(1)).append(" ");
    }
    return result.toString().trim();
}
回复
阅读 848
5 个回答
边城
  • 54.8k
四川
✓ 已被采纳

来用正则表达式

package playground.sf.q1010000042250246;

import java.util.regex.Pattern;

public class Solution {
    public static void main(String[] args) {
        final String s = "hello world. How are you.";
        System.out.println(capitalCase(s));
    }

    private static String capitalCase(String s) {
        var m = Pattern.compile("(?<=^|\\s)[a-z]").matcher(s);
        StringBuilder builder = new StringBuilder();
        while (m.find()) {
            m.appendReplacement(builder, m.group().toUpperCase());
        }
        return m.appendTail(builder).toString();
    }
}

逐一遍历法

    private static String capitalCase(String s) {
        StringBuilder builder = new StringBuilder(s);
        char last = ' ';
        for (int i = 0; i < s.length(); last = builder.charAt(i++)) {
            if (!Character.isSpaceChar(last)) { continue; }
            char ch = builder.charAt(i);
            if (!Character.isSpaceChar(ch)) {
                builder.setCharAt(i, Character.toUpperCase(ch));
            }
        }
        return builder.toString();
    }

查找法

    private static String capitalCase(String s) {
        if (s.length() <= 1) { return s.toUpperCase(); }

        StringBuilder builder = new StringBuilder();
        builder.append(Character.toUpperCase(s.charAt(0)));
        int start = 1;
        while (start > 0) {
            int end = s.indexOf(' ', start);
            if (end <= 0) {
                builder.append(s, start, s.length());
                break;
            }

            while (Character.isSpaceChar(++end));
            builder.append(s, start, end);
            builder.append(Character.toUpperCase(s.charAt(end++)));
            start = end;
        }
        return builder.toString();
    }

因为小写字母比大写字母的ascii码值大32,所以减去32即可得到大写字母,当然这种写法首字母必须是小写才行

        String str = "user password";
        String[] arr = str.split(" ");
        for (int i = 0; i < arr.length; i++) {
            char[] chars = arr[i].toCharArray();
            chars[0] -= 32;
            arr[i] = String.valueOf(chars);
        }

    public String convert(Character c, String s) {
        StringBuilder out = null;
        int i = 0;
        int j = -1;
        while ((j = indexIn(s, ++j, c)) != -1) {
            out = new StringBuilder(s.length() + 4 * c.toString().length());
            out.append(firstCharOnlyToUpper(s.substring(i, j)));
            out.append(c);
            i = j + c.toString().length();
        }
        return out.append(firstCharOnlyToUpper(s.substring(i))).toString();
    }

    private int indexIn(CharSequence sequence, int start, char c) {
        int length = sequence.length();
        for (int i = start; i < length; i++) {
            if (sequence.charAt(i) == c) {
                return i;
            }
        }
        return -1;
    }


    private String firstCharOnlyToUpper(String word) {
        return word.isEmpty() ? word : Ascii.toUpperCase(word.charAt(0)) + Ascii.toLowerCase(word.substring(1));
    }
Mannix
  • 1.2k
广东

for 循环中的 result.trim(); 可以去掉

正则的写法

Pattern initialRE = Pattern.compile("\\b\\p{javaLowerCase}"); // 只要开头或空格后的字母则用 (?<=^| )\\p{javaLowerCase}
String res = initialRE.matcher("user password").replaceAll(m -> m.group().toUpperCase());
System.out.println(res); // User Password

原始且高性能的写法

char[] cs = "user password".toCharArray();
for (int i = 0, len = cs.length; i < len; ++i) {
  char c = cs[i];
  if (c == ' ') continue;
  cs[i] = Character.toTitleCase(c); // 这个支持特殊 unicode 字符,如 dz 是 Dz 而不是 DZ
  while (++i < len && cs[i] != ' ');
}
String res = new String(cs);
System.out.println(res); // User Password
SanJinYe88
  • 5
北京市新手上路,请多包涵

这个简单:

    public static void main(String[] args) {
        String str = "user name";
        StringBuilder sb = new StringBuilder("");
        String[] s = str.split(" ");
        for (int i = 0; i < s.length; i++){
            if(StringUtils.isNotEmpty(s[i])){
                sb.append(StringUtils.capitalize(s[i])).append(" ");
            }
        }
        System.out.println(sb);
    }

运行结果:
image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏