我需要创建一个程序来移动用户输入的字符串中的单词。用户将输入一个句子并输入他们想要移动的单词数。如果用户输入“我有一只名为Spot的狗”然后输入2,则输出将是“命名为Spot I have a dog”。我真的不确定如何解决这个问题。我编写的代码是为了颠倒我刚写的字符串的顺序,但我不确定这是否适用于此。它甚至都不起作用。我无法弄清楚如何使它发挥作用。
我重写了一些代码。我现在有这个。但它表示输入不匹配。
答案 0 :(得分:1)
你是对的,扭转字符串对你没有帮助。我建议使用tokenization在空格上拆分字符串,然后根据此数组构建字符串。
get input string and number of words to be moved from user
tokenize input string on spaces
if number of tokens is greater than number of words to be moved then
build a new string starting with the number of words needed from the end of the tokens
add the rest of the tokens from the beginning of the tokens
endif
您现有的代码非常接近这一点,您已经将输入字符串标记化了,但是然后再向后构建它,这比您需要的工作要多得多。您可以从标记数组的末尾获取所需的单词数,然后开始构建类似的字符串。
我会给你代码,但我怀疑这是一个学校项目,这无助于教育你。
答案 1 :(得分:0)
反转字符串可能与此无关。但我建议在发布之前尝试某事。
一个想法可能是将单词拆分为列表/数组并尝试旋转列表中的每个元素。这有帮助吗?
答案 2 :(得分:0)
使用模数进行旋转:
String s = "I have a dog named Spot";
String[] words = s.split(" ");
int ROT = 2;
for(int i = 0; i < words.length; i++)
System.out.print(words[(i + words.length - ROT)%words.length] + " ");
OUTPUT:名为Spot我有一只狗
答案 3 :(得分:0)
我有答案。
但是,如果这是算法的功课,你应该自己思考。
我只建议使用java内置类的示例。
String str = "Please think of other answer if this is homework";
List<String> list = new LinkedList<String>(Arrays.asList(str.split(" ")));
Collections.rotate(list, 3);
StringBuffer sb = new StringBuffer();
for(String s:list){
sb.append(s).append(" ");
}
System.out.println(sb);//"this is homework Please think of other answer if "