在java中反转句子
我在我的程序中插入一个字符串
String str = " I live in India";
怎么能得到反转的那样的字符串
String str ="India in live I"
这是我在采访中的一个面试问题。 请任何人都可以帮我解决这个问题
拆分它然后以相反的顺序将它添加到新的String
中。
String s = " I live in India"; String[] split = s.split(" "); String result = ""; for (int i = split.length - 1; i >= 0; i--) { result += (split[i] + " "); } System.out.println(result.trim());
这打印:
India in live I
String str = "I live in India"; String result = ""; String[] words = str.split(" "); for (int i=words.length-1;i>=0;i--){ result = result + words[i] + " "; } result = result.subString(result, 0, result.length-1); // remove the last " "
此代码沿着空格分割字符串,以便您获得单词的数组。 然后for循环遍历数组从最后一个元素到第一个元素,并将单词加上一个空格附加到结果字符串。 最后删除最后一个单词后的空格。
试试这种方式
public class test { public static void main(String args[]) { String x="i live in india"; String y[]=x.split(" "); System.out.println(y[3]+" "+y[2]+" "+y[1]+" "+y[0]); // if the input string is different meaning if the number of words are greater than or less than four then try this way /*for(int i=y.length-1;i>=0;i--) { System.out.print(y[i]+ " "); }*/ } }
这是显示输出的屏幕截图