用Java反转“Hello World”string中的每个单词
我想在Java中反转每个string(不是整个string,只是每个单词)。
例如:如果inputstring是“Hello World”,那么输出应该是“olleH dlroW”。
这应该做的伎俩。 这将迭代源string中的每个单词,使用StringBuilder
的内置reverse()
方法将其反转,并输出反转的单词。
String source = "Hello World"; for (String part : source.split(" ")) { System.out.print(new StringBuilder(part).reverse().toString()); System.out.print(" "); }
输出:
olleH dlroW
注:评论者正确地指出了一些我认为应该在这里提到的事情。 这个例子会在结果的末尾附加一个额外的空格。 它也假设你的话是由一个单独的空间分隔,而你的句子不包含标点符号。
知道你的图书馆;-)
import org.apache.commons.lang.StringUtils; String reverseWords(String sentence) { return StringUtils.reverseDelimited(StringUtils.reverse(sentence), ' '); }
split
成单词array
后,您需要对每个单词执行此操作。
public String reverse(String word) { char[] chs = word.toCharArray(); int i=0, j=chs.length-1; while (i < j) { // swap chs[i] and chs[j] char t = chs[i]; chs[i] = chs[j]; chs[j] = t; i++; j--; } return String.valueOf(chs); }
这是最简单的解决scheme,甚至不使用任何循环。
public class olleHdlroW { static String reverse(String in, String out) { return (in.isEmpty()) ? out : (in.charAt(0) == ' ') ? out + ' ' + reverse(in.substring(1), "") : reverse(in.substring(1), in.charAt(0) + out); } public static void main(String args[]) { System.out.println(reverse("Hello World", "")); } }
即使这是作业,随意复制并提交它作为你自己的。 你会得到一个额外的信用(如果你能解释它是如何工作的)或被抄袭(如果你不能)。
这里没有人考虑unicode字符。 您需要使用java.text.BreakIterator
来查找单词边界,然后在每个单词边界内使用另一个单词来枚举字符边界:
String helloWorld = "He\u0308llo World"; // Hëllo World StringBuilder reverseStringBuilder = new StringBuilder(helloWorld.length()); BreakIterator wordBreakIterator = BreakIterator.getWordInstance(); wordBreakIterator.setText(helloWorld); int wordStart = wordIterator.first(); int wordEnd = wordIterator.next(); while (wordEnd != BreakIterator.DONE) { String word = helloWorld.substring(wordStart,wordEnd); if (Character.isLetterOrDigit(word.charAt(0))) { // "Hello" or "World" in our example BreakIterator characterBreakIterator = BreakIterator.getCharacterInstance(); characterBreakIterator.setText(word); int characterEnd = characterBreakIterator.last(); int characterStart = characterBreakIterator.previous(); while (characterStart != BreakIterator.DONE) { reverseStringBuilder.append(word.substring(characterStart, characterEnd)); characterEnd = characterStart; characterStart = characterBreakIterator.previous(); } } else { // " " in our example reverseStringBuilder.append(word); } wordStart = wordEnd; wordEnd = wordIterator.next(); } String dlroWolleh = reverseStringBuilder.toString(); // "dlroW ollëH"
使用上面的\u0308
方法会在String
反转时改变第一个字符以上的变音符号。 你希望它保持在e
之上。
那么我是一个C / C + +的人,练习java面试让我知道,如果有什么可以改变或改善。 以下允许多个空格和换行符。
首先是使用StringBuilder
public static String reverse(String str_words){ StringBuilder sb_result = new StringBuilder(str_words.length()); StringBuilder sb_tmp = new StringBuilder(); char c_tmp; for(int i = 0; i < str_words.length(); i++){ c_tmp = str_words.charAt(i); if(c_tmp == ' ' || c_tmp == '\n'){ if(sb_tmp.length() != 0){ sb_tmp.reverse(); sb_result.append(sb_tmp); sb_tmp.setLength(0); } sb_result.append(c_tmp); }else{ sb_tmp.append(c_tmp); } } if(sb_tmp.length() != 0){ sb_tmp.reverse(); sb_result.append(sb_tmp); } return sb_result.toString(); }
这一个是使用char []。 我认为它更高效…
public static String reverse(String str_words){ char[] c_array = str_words.toCharArray(); int pos_start = 0; int pos_end; char c, c_tmp; int i, j, rev_length; for(i = 0; i < c_array.length; i++){ c = c_array[i]; if( c == ' ' || c == '\n'){ if(pos_start != i){ pos_end = i-1; rev_length = (i-pos_start)/2; for(j = 0; j < rev_length; j++){ c_tmp = c_array[pos_start+j]; c_array[pos_start+j] = c_array[pos_end-j]; c_array[pos_end-j] = c_tmp; } } pos_start = i+1; } } //redundant, if only java had '\0' @ end of string if(pos_start != i){ pos_end = i-1; rev_length = (i-pos_start)/2; for(j = 0; j < rev_length; j++){ c_tmp = c_array[pos_start+j]; c_array[pos_start+j] = c_array[pos_end-j]; c_array[pos_end-j] = c_tmp; } } return new String(c_array); }
我假设你可以打印结果(你只是说'输出应该是…');-)
String str = "Hello World"; for (String word : str.split(" ")) reverse(word); void reverse(String s) { for (int idx = s.length() - 1; idx >= 0; idx--) System.out.println(s.charAt(idx)); }
或者返回反转的string:
String str = "Hello World"; StringBuilder reversed = new StringBuilder(); for (String word : str.split(" ")) { reversed.append(reverse(word)); reversed.append(' '); } System.out.println(reversed); String reverse(String s) { StringBuilder b = new StringBuilder(); for (int idx = s.length() - 1; idx >= 0; idx--) b.append(s.charAt(idx)); return b.toString(); }
只使用substring()
和recursion:
public String rev(String rest) { if (rest.equals("")) return ""; return rev(rest.substring(1)) + rest.substring(0,1); }
考虑到分隔符可以多于一个空格/标签,并且我们要保留它们:
public static String reverse(String string) { StringBuilder sb = new StringBuilder(string.length()); StringBuilder wsb = new StringBuilder(string.length()); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (c == '\t' || c == ' ') { if (wsb.length() > 0) { sb.append(wsb.reverse().toString()); wsb = new StringBuilder(string.length() - sb.length()); } sb.append(c); } else { wsb.append(c); } } if (wsb.length() > 0) { sb.append(wsb.reverse().toString()); } return sb.toString(); }
下面是一个方法,它接受一个string并将其反转。
public String reverse ( String s ) { int length = s.length(), last = length - 1; char[] chars = s.toCharArray(); for ( int i = 0; i < length/2; i++ ) { char c = chars[i]; chars[i] = chars[last - i]; chars[last - i] = c; } return new String(chars); }
首先,你需要将string拆分成像这样的单词
String sample = "hello world"; String[] words = sample.split(" ");
在解决这个问题的时候,我想出了这个答案。 我试图不使用嵌套for循环解决schemeO(N ^ 2)。 我有点强迫自己使用堆栈的乐趣:D
public StringBuilder reverseWord(String input) { char separator = ' '; char[] chars = input.toCharArray(); Stack<Character> stack = new Stack<Character>(); StringBuilder sb = new StringBuilder(chars.length); for(int i = 0; i < chars.length; i++) { if(chars[i] != separator) { //letters stack.push(chars[i]); //if not last letter don't go any further if(i != chars.length - 1) { continue; } } while(!stack.isEmpty()) { sb.append(stack.pop()); } sb.append(separator); } //remove the last separator sb.deleteCharAt(sb.length() - 1); return sb; }
String input = "Hello World!"; String temp = ""; String result = ""; for (int i = 0; i <= input.length(); i++) { if (i != input.length() && input.charAt(i) != ' ') { temp = input.charAt(i) + temp; } else { result = temp + " " + result; temp = ""; } } System.out.println("the result is: " + result);
public static void main(String[] args) { System.out.println(eatWord(new StringBuilder("Hello World This Is Tony's Code"), new StringBuilder(), new StringBuilder())); } static StringBuilder eatWord(StringBuilder feed, StringBuilder swallowed, StringBuilder digested) { for (int i = 0, size = feed.length(); i <= size; i++) { if (feed.indexOf(" ") == 0 || feed.length() == 0) { digested.append(swallowed + " "); swallowed = new StringBuilder(); } else { swallowed.insert(0, feed.charAt(0)); } feed = (feed.length() > 0) ? feed.delete(0, 1) : feed ; } return digested; }
跑:
olleH dlroW sihT sI s'ynoT edoC BUILD SUCCESSFUL (total time: 0 seconds)
使用split(),你只需要改变你想分裂的东西。
public static String reverseString(String str) { String[] rstr; String result = ""; int count = 0; rstr = str.split(" "); String words[] = new String[rstr.length]; for(int i = rstr.length-1; i >= 0; i--) { words[count] = rstr[i]; count++; } for(int j = 0; j <= words.length-1; j++) { result += words[j] + " "; } return result; }
String someString = new String("Love thy neighbor"); System.out.println(someString); char[] someChar = someString.toCharArray(); int j = someChar.length - 1; char temp; for (int i = 0; i <= someChar.length / 2; i++) { temp = someChar[i]; someChar[i] = someChar[j]; someChar[j] = temp; j--; } someString = new String(someChar); System.out.println(someString);
跑:
Love thy neighbor robhgien yht evoL
class ReverseWordsInString{ public static String reverse(String s1){ int l = s1.length(); if (l>1) return(s1.substring(l-1) + reverse(s1.substring(0,l-1))); else return(s1.substring(0)); } public static void main(String[] args){ String st = "Hello My World!"; String r = ""; for (String word : st.split(" ")) r += " "+ reverse(word); System.out.println("Reversed words in the given string: "+r.trim()); } }
使用split()函数并反转单个单词
public String reverseSentence(String input) { String[] words = input.split(" "); StringBuilder builder = new StringBuilder(); for (String s : words) { String rev = " "; for (int i = 0; i < s.length(); i++) { rev = s.charAt(i) + rev; } builder.append(rev); } return builder.toString().trim(); }
使用trim()移除新string末尾添加的额外空间
输出:
This is my sentence sihT si ym ecnetnes
public String reverse(String arg) { char[] s = arg.toCharArray(); StringBuilder sb = new StringBuilder(); boolean reverse = false; boolean isChar = false; int insertPos = 0; for (int i = 0; i < s.length; i++) { isChar = Character.isAlphabetic(s[i]); if (!reverse && isChar) { sb.append(s[i]); insertPos = i; reverse = true; } else if (reverse && isChar) { sb.insert(insertPos, s[i]); } else if (!reverse && !isChar) { sb.append(s[i]); } else if (reverse && !isChar) { reverse = false; sb.append(s[i]); } } return sb.toString(); }
package MujeebWorkspace.helps; // javamujeeb@gmail.com public class Mujeeb { static String str= "This code is simple to reverse the word without changing positions"; static String[] reverse = str.split(" "); public static void main(String [] args){ reverseMethod(); } public static void reverseMethod(){ for (int k=0; k<=reverse.length-1; k++) { String word =reverse[reverse.length-(reverse.length-k)]; String subword = (word+" "); String [] splitsubword = subword.split(""); for (int i=subword.length(); i>0; i--){ System.out.print(splitsubword[i]); } } } }
String input = "Welcome To The Java Programming"; String output = ""; String[] cutAry = input.split("\\s+"); StringBuilder sb = new StringBuilder(); for(String s:cutAry){ sb.append(s); output += sb.reverse().toString()+" "; sb.replace(0, sb.length(), ""); } System.out.println(output);
with and without api. public class Reversal { public static void main(String s[]){ String str= "hello world"; reversal(str); } static void reversal(String str){ String s[]=str.split(" "); StringBuilder noapi=new StringBuilder(); StringBuilder api=new StringBuilder(); for(String r:s){ noapi.append(reversenoapi(r)); api.append(reverseapi(r)); } System.out.println(noapi.toString()); System.out.println(api.toString()); } static String reverseapi(String str){ StringBuilder sb=new StringBuilder(); sb.append(new StringBuilder(str).reverse().toString()); sb.append(' '); return sb.toString(); } static String reversenoapi(String str){ StringBuilder sb=new StringBuilder(); for(int i=str.length()-1;i>=0;i--){ sb.append(str.charAt(i)); } sb.append(" "); return sb.toString(); } }
我知道这是一个旧的post,但是如果它能帮助某人的话,我会认为要写出答案。 请使用下面的代码来解决问题。
public static void main(String[] args) { // TODO Auto-generated method stub String string1 = "Hello how are you"; String[] string2 = string1.split(" "); String result =""; for(int i=0;i<string2.length;i++) { StringBuilder stringBuilder = new StringBuilder(string2[i]); result = (i==0)?(result+ stringBuilder.reverse().toString()):(result +" "+stringBuilder.reverse().toString()); } System.out.println("Result line:"+result); }
文本显示在控制台中:结果行:olleH woh era uoy
以块为单位反向复制string,然后连接空格。 例如。 “你好java世界”。
1st block =“hello”反向复制它: – “olleh”,然后添加空格
第二块=“java”等
public static void main(String args[]) { String s, rev = ""; Scanner in = new Scanner(System.in); System.out.println("Enter a string to reverse"); s = in.nextLine(); int length = s.length(); // char[] cs=s.toCharArray(); int l, r; int i = 0; while (i < length) { l = i; // starting index // find length of sub-block to reverse copy while (i < length && s.charAt(i) != ' ') { i++; } r = i - 1; // ending index for (int j = r; j >= l; j--) { // copy reverse of sub-block rev = rev + s.charAt(j); } rev = rev + " "; // add the whitespace i++; } System.out.println("Reverse of entered string is: " + rev); }
程序也适用于单词之间的多个空格。
上面的一些解决scheme的运行时间较高的复杂性。 用下面的algorithm,可以在O(n)时间内完成。
algorithm:
- 从结尾开始parsingstring。
- 每遇到一个空格字符,即“”,将parsing的字符列表放到一个可以dynamic增长的ArrayList中。
- 按照相反的顺序打印ArrayList,从而为您提供所需的输出。
复杂度:O(n)其中n是string的长度。
import java.io.IOException; import java.util.ArrayList; public class WordReverse { public static void main(String[] args) throws IOException { String inputStr = "Hello World"; String reversed = ""; ArrayList<String> alist = new ArrayList<String>(); for (int i = inputStr.length() - 1; i >= 0; i--) { if (inputStr.charAt(i) != ' ') { reversed = reversed + inputStr.charAt(i); } else { alist.add(reversed); reversed = ""; } } alist.add(reversed); String result = ""; for (int i = alist.size() - 1; i >= 0; i--) { result = result + alist.get(i); result = result + " "; } System.out.println(result); } }
这是我的版本与相同的数字空间。 希望你喜欢它的家伙!
public String reverseWords(String text){ StringBuilder out = new StringBuilder(); for(String word : text.split(" ")){ out.append(new StringBuilder(word).reverse().toString()); out.append(" "); } return out.toString().substring(0, out.length() - 1); }
这反转给定的string中的单词。 单词被假定为由一个空格分开。 反转是在适当的位置完成的(在字符缓冲区中)。
public static String reversePhrases(String s) { char[] buf = s.toCharArray(); int len = buf.length; int start = 0; for (int i = 0; i < len; i++) { if (buf[i] == ' ' || i == (len-1)) { if (i == (len-1)) { i = len; } int end = (start + i)/2; for (int j = start; j < end; j++) { char c = buf[j]; int pos = (start + i) - j - 1; buf[j] = buf[pos]; buf[pos] = c; } start = i + 1; } } return new String(buf); }
最简单的方法之一:
public String reverse(String post) { String backward = ""; for(int i = post.length()-1; i >= 0; i--) { backward = backward + post.substring(i, i+1); } return backward; }
简单的方法:
String reverseString(String string) { String newString = ""; for(int x = string.length() - 1; x > -1; x ++) newString += string.charAt(x); return newString; }
如果它反转每个字母比这个for循环很好地工作:
for(int i = 0; i < input.length(); i++){ output = output + input.substring((input.length()-i)-1, input.length()-i); }
我希望这对某个人有用。
public class ReverseString { public static void main(String[] args) { String a="abrakadabra"; String b=reverse(a); System.out.print(b); } public static String reverse(String b){ String j=""; int a=b.length(); for (int x=a;x>0;x--){ j=j+b.substring(x-1,x);} return j; } }