我会再问一次。我有一个问题,那就是创建一个程序来读取用户输入的字符串(句子或单词)。并且第N个数字(来自用户)将变为大写,其余的将变为小写。示例:
string =“大家早上好]
n = 2
输出=方式eVeryone
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);
}
输出:大家早上好
我知道您想发生什么-但您对问题的措辞不太好。您缺少的唯一部分是遍历句子中的每个单词。如果您问“我如何在字符串中的每个单词上应用函数”,您可能会得到更好的答复。
这有点草率,因为它在末尾添加了尾随的“”-但您可以轻松地修复它。
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;
}
}
您可以使用两个for循环来执行此操作。遍历每个单词,并在迭代过程中遍历每个字符。
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);
}