【问题标题】:Turning the Nth (input from user) number into Uppercase and the rest will be in Lowercase将第 N 个(用户输入)数字转换为大写,其余为小写
【发布时间】:2023-03-26 18:54:01
【问题描述】:

我会再问一次。我有这个问题,即创建一个程序来读取用户输入的字符串(句子或单词)。并且第 N 个数字(来自用户)将变为大写,其余的将变为小写。 示例:

string = "大家早上好"

n = 2

输出 = 早上好,每个人

    for (int x = 0; x < s.length(); x++)
        if (x == n-1){
            temp+=(""+s.charAt(x)).toUpperCase();
        }else{
            temp+=(""+s.charAt(x)).toLowerCase();
        }
    s=temp;
    System.out.println(s);
}

输出:大家早上好

【问题讨论】:

  • 那么 - 有什么问题?你有什么问题。
  • 你有一个基于每个单词的功能。因此,遍历单词并将您的函数应用于每个单词。
  • 你从来没有在问题的任何地方写过你想让n输入的每个单词都是大写的,它实际上只在Output行上看到。你也没有真正问过问题。
  • 我想我在句子的第一个单词中得到了它,但我不知道如何在下一个单词中再次这样做,因为它之间包含空格

标签: java string ms-word uppercase lowercase


【解决方案1】:

我知道你想要发生什么 - 但你没有很好地表达你的问题。您唯一缺少的部分是遍历句子中的每个单词。如果您问“我如何对字符串中的每个单词应用函数”,您可能会得到更好的回答。

这有点草率,因为它在末尾添加了一个尾随“” - 但您可以轻松解决这个问题。

public class Test {

    static String test = "This is a test.";

    public static void main(String[] args) {
        String[] words = test.split(" ");
        String result = "";

        for (String word : words) {
            result += nthToUpperCase(word, 2);
            result += " ";
        }

        System.out.println(result);
    }

    public static String NthToUpperCase(String s, int n) {
        String temp = "";

        for (int i = 0; i < s.length(); i++) {
            if (i == (n-1)) {
                temp+=Character.toString(s.charAt(i)).toUpperCase();
            } else {
                temp+=Character.toString(s.charAt(i));
            }
        }

        return temp;
    }
}

【讨论】:

    【解决方案2】:

    您可以使用两个 for 循环来做到这一点。迭代每个单词并在迭代内迭代每个字符。

    toUpperCase(2, "good morning everyone");
    
    private static void toUpperCase(int nth, String sentence) {
        StringBuilder result = new StringBuilder();
        for(String word : sentence.split(" ")) {
            for(int i = 0; i < word.length(); i++) {
                if(i > 0 && i % nth - 1 == 0) {
                    result.append(Character.toString(word.charAt(i)).toUpperCase());
                } else {
                    result.append(word.charAt(i));
                }
            }
            result.append(" ");
        }
        System.out.println(result);
    }
    

    祝大家早日康复

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-28
      • 2013-11-29
      • 2019-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多