将字符串中的各种字母大写 [英] Capitalize various letters in a string

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

问题描述

我正在处理一个面试问题:

I am working on an interview question:

将字符串中的第 2、4、8、16 个字母大写

Capitalize 2nd, 4th, 8th, 16th letters in a string

输入 - 字符串中的字母"

input - "letters in a string"

输出 - 字符串中的字母"

output - "lEtTers in a stRing"

这是我的解决方案:

public static void main(String[] args) {
    String input = "letters in a string";

    String output = input.substring(0, 1) + input.substring(1, 2).toUpperCase() + input.substring(2, 3)
            + input.substring(3, 4).toUpperCase() + input.substring(4, 7) + input.substring(7, 8).toUpperCase()
            + input.substring(8, 15) + input.substring(15, 16).toUpperCase() + input.substring(15);
    System.out.println(output);

}

有什么方法可以在不硬编码偏移量的情况下对此进行概括?一般来说,我正在寻找的是 - 给定我们想要大写的字母数字,我们的程序应该在不改变核心逻辑的情况下工作,并且在复杂性方面也应该是高效的?

Is there any way we can generalize this without hard coding the offset numbers here? In general, what I am looking for is - given the letter number which we want to capitalize, our program should work on that without changing the core logic and should be efficient as well in terms of complexity?

推荐答案

假设您希望将角色的幂的范围设置为 2 (2, 4, 8, 16, 32, 64...),你可以简单地使用一个循环.

Assuming that you want to set the character at an ever increasing range of power by 2 (2, 4, 8, 16, 32, 64...), you could simply use a loop.

问题是,String 不是可变的(它不能改变),你应该尽可能避免循环中的 String 连接(好吧,就你而言,这可能没什么大不了的,但它仍然是一个很好的做法).

The problem is, String isn't mutable (it can't be changed) and you should avoid String concatenation within loops where possible (okay, in your case, it's probably not a big deal, but it's still good practice).

为此,您可以将 String 转换为 char 数组 (String#toCharArray()) 或使用 StringBuilder,例如...

To that end, you could either convert the String to a char array (String#toCharArray()) or use a StringBuilder, for example...

String text = "letters in a string";
int index = 2;
StringBuilder sb = new StringBuilder(text);
while (index < sb.length()) {
    sb.setCharAt(index - 1, Character.toUpperCase(sb.charAt(index - 1)));
    index *= 2;
    System.out.println(index);
}

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

输出字符串中的字母

这篇关于将字符串中的各种字母大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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