Reverse the order of sentence words according to the index range

Topic information

Given a sentence, each word in the sentence is separated by a space, given a word range, reverse the order of the words in the range. For example, given a sentence i am a student. Given a word range of 1 to 3, the result after flipping is i student. a am

  • Example input i am a student. 1 3
  • Example output i student. a am

answer

According to the topic information, the following information can be roughly derived:

  1. Three parameter information must be received and used by the program
  2. The words are separated by spaces. After the sentence is given, you need to use split to split the words
  3. Traverse the divided words and reverse the order of words in a given range

coding

package com.questionbank.nowcoder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReverseControlWords {

	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String input;
	
		// 定义索引位置,方便接收参数值
		int index = 0;
		
		// 定义三个变量,分别接收句子,起始和结束索引范围
		String sentence = null;
		int start = 0;
		int end = 0;
		while ((input = br.readLine()) != null) {
			// 根据不同索引位置,将接收的输入值赋给不同变量
			if (index == 0) {
				sentence = input;
			} else if (index == 1) {
				start = Integer.valueOf(input);
			} else {
				// 在拿到第三个变量值后,进行逆序处理
				end = Integer.valueOf(input);
				reverseSentence(sentence, start, end);
			}
			
			// 参数位置后移
			index++;
			
			// 逆序后,索引置0
			if (index == 3) {
				index = 0;
			}
		}
	}
	
	public static void reverseSentence(String sentence, int start, int end) {
		String[] words = sentence.split(" ");
		StringBuilder sb = new StringBuilder();
		
		// 遍历单词数组
		for (int i=0; i<words.length; i++) {
			
			// i等于start且小于end时,对单词逆序处理
			if (i == start && i<end) {
				String tmp = words[i];
				words[i] = words[end];
				words[end] = tmp;
				
				// 逆序后,start位置后移,end位置前移
				start++;
				end--;
			}
			
			sb.append(words[i]).append(" ");
		}
		
		// 输出截取后的结果值
		System.out.println(sb.substring(0, sb.length()-1));
	}
}

 

Guess you like

Origin blog.csdn.net/magi1201/article/details/114462108