java - 如何在java中访问字符串数组的每个元素?
问题描述
我正在编写一个函数来反转字符串中单词的位置而不反转单词本身。但我无法访问字符串数组的元素。我收到以下代码错误。
public static void reverseWords(String sd[]) {
for(String s : sd){
System.out.println(s);
}
}
解决方案
要反转字符串数组中的单词,请执行以下操作。
public class Reverse{
public static void main(String[] args){
String[] stringArray = {"Jim", "Jeff", "Darren", "Michael"};
reverseWords(stringArray);
for(String strings : stringArray) {
System.out.println(strings);
}
}
public static void reverseWords(String[] array) {
for(int i=0; i<array.length/2; i++) {
String temp = array[array.length-1-i];
array[array.length-1-i] = array[i];
array[i] = temp;
}
}
}
输出 :
Michael
Darren
Jeff
Jim
要将字符串作为输入,请尝试以下操作。
public class Reverse{
public static void main(String[] args){
String sentence = "Bob went to the store";
String newSentence = reverseWords(sentence);
System.out.println(newSentence);
}
public static String reverseWords(String sentence) {
//This line splits the String sentence by the delimiter " " or by a space
String[] array = sentence.split(" ");
//for loop to reverse the array
for(int i=0; i<array.length/2; i++) {
String temp = array[array.length-1-i];
array[array.length-1-i] = array[i];
array[i] = temp;
}
//These next 4 lines simply take each element in the array
//and concatenate them all into one String, reversedSentence.
String reversedSentence = "";
for(int i=0; i<array.length; i++) {
//This if statement ensures that no space (" ") is concatenated
//to the end of the reversedSentence.
if(i == array.length-1) {
reversedSentence += array[i];
continue;
}
reversedSentence += array[i] + " ";
}
//returning the newly created reversedSentence!
return reversedSentence;
}
}
输出 :
store the to went Bob
希望这可以帮助!
推荐阅读
- c++ - 带有向量的变量范围的最佳实践
- flutter - Stack 小部件不能作为 Column 小部件的子级工作
- c++ - 多次包含 GetPot
- javascript - 为什么 rxjs 共享运算符在这个 setTimeout() 示例中不能按预期工作?
- listbox - PowerApps - 列表框 - 将选定的值更新到 SP 列表中
- php - 循环多维数组 PHP
- ios - Swift如何检测推送通知权限何时从系统设置更改?
- c++ - 模板类型的类模板参数推导本身就是模板的参数
- java - 通过 Jenkins 将战争部署到 jboss eap 时出错
- python-3.x - 如何从输出中排除引号?