我试着把每个句子的第二个词都倒过来
如果给定的字符串是:
My name is xyz
所需输出应为:
My eman is zyx
我的当前输出是:
Ym eman s1 zyx
我无法实现我想要的输出。不知道我做错了什么
这是我的代码
char[] sentence = " Hi my name is person!".toCharArray();
System.out.println(ReverseSentence(sentence));
}
private static char[] ReverseSentence(char[] sentence)
{
//Given: "Hi my name is person!"
//produce: "iH ym eman si !nosrep"
if(sentence == null) return null;
if(sentence.length == 1) return sentence;
int startPosition=0;
int counter = 0;
int sentenceLength = sentence.length-1;
//Solution handles any amount of spaces before, between words etc...
while(counter <= sentenceLength)
{
if(sentence[counter] == ' ' && startPosition != -1 || sentenceLength == counter) //Have passed over a word so upon encountering a space or end of string reverse word
{
//swap from startPos to counter - 1
//set start position to -1 and increment counter
int begin = startPosition;
int end;
if(sentenceLength == counter)
{
end = counter;
}
else
end = counter -1;
char tmp;
//Reverse characters
while(end >= begin){
tmp = sentence[begin];
sentence[begin] = sentence[end];
sentence[end] = tmp;
end--; begin++;
}
startPosition = -1; //flag used to indicate we have no encountered a character of a string
}
else if(sentence[counter] !=' ' && startPosition == -1) //first time you encounter a letter in a word set the start position
{
startPosition = counter;
}
counter++;
}
return sentence;
}
7条答案
按热度按时间wixjitnu1#
如果你想反转替代单词,你可以尝试将整个
String
分割成由空格分隔的单词,并在每个第二个单词上应用StringBuilder reverse()
,如:-输出:-
My eman is zyx
vnzz0bqm2#
你可以用各种简单的方法来解决你的问题!只要使用一个
flag
变量,它将指示 even 或 odd 位置,更准确地说,任何单词是否会被反转!看看我在你的代码中做的以下修改,只是增加了三行:
输入
我叫xyz
输出:
我的男人是zyx
yxyvkwin3#
下面的代码执行这个“特殊反转”,它反转了句子中的任何其他单词:
deyfvvtc4#
为了完整起见,这里是Java-8解决方案:
57hvy0tb5#
xxe27gdn6#
//在java public class ReverseSecondWord中反转句子的第二个单词{
}
myss37ts7#
导入java。util.扫描仪;
public class Reverse_alternate_word { public static String reverseWord(String str){ // input:我的名字是rohit char ch;//输出:我的男人是tihor String rev="";
}