Я пытаюсь обратить каждые 2 слова каждого предложения, какReverse каждые 2 слова предложения
Если данная строка:
My name is xyz
Желательный результат должен быть:
My eman is zyx
Мой выходной ток:
Ym eman s1 zyx
Я не в состоянии достичь желаемого мой output.Don't знаю, что я делаю неправильно здесь
Вот мой код
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;
}
Я запутался, как к вашим требованиям. Итак, вы хотите изменить любое другое слово? Просьба уточнить, что именно вы пытаетесь сделать. –
Что такое рисунок здесь, вы хотите, чтобы даже слово позиции было отменено? – Bhupi
Как указано, ваш вопрос неясен. Для этого есть готовая библиотека (реверсивный метод с обратной связью) https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#reverse (java.lang.String)? Но не знаю, чего вы хотите достичь. У меня такое же понимание проблемы, как MadConan –