我有一个代码,可以使单词逐字颠倒,例如,输入是"stack overflow“,输出将是”kcat wolfrevo“,但问题是当我输入"stack,overflow”时。输出将是",kcat .wolfrevo“而不是”kcat,wolfrevo“。
有没有办法让这个特殊字符留在他的索引中?我只知道java编程的基础知识。
我的代码:
Scanner input = new Scanner(System.in);
System.out.print("Enter a Paragraph: ");
String str = input.nextLine();
String[] Words = new String[countWords(str)];
int temp = str.length()-1;
for (int j = 0; j < countWords(str); j++) {
String reverse = "";
loop:
for (int i=temp;i>=0;i--) {
if (str.charAt(i) == ' ') {
temp=temp-1;
break;
}
temp=temp-1;
reverse = reverse + str.charAt(i);
}
Words[j]=reverse;
}
for (int i = countWords(str)-1;i>=0;i--) {
System.out.print(Words[i]+" ");
}
}
protected static int countWords(String str) {
int count = 0;
if (!(" ".equals(str.substring(0, 1))) || !(" ".equals(str.substring(str.length() - 1)))) {
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') {
count++;
}
}
count = count + 1;
}
return count;
}发布于 2019-02-11 19:46:28
我已经写了一个小的Python草图,它可以做你想要的。我知道它不是Java,但它的功能是基本的,应该很容易翻译成java。我添加了一些评论来指导你:
def split(string, seperators): # parameters dont have types in Python. Imagine (String string, String separators) here
words = []
while True:
j = len(string)
if j == 0:
break
for sc in seperators: # iterate over all chars in seperators string
try:
i = string.index(sc)
if i < j:
j = i
except ValueError: # This is like try-catch. ValueError is thrown when no value is found. Java returns -1 when str.indexOf(char) isn't found
continue
nextWord = string[:j] # this means substring(0, j)
if nextWord:
words.append(nextWord)
words.append(string[j:j+1]) # this means substring(j, j+1)
string = string[j+1:] # this means substring(j+1)
return words
def reverse(string): # Imagine (String string) here
words = split(string, "., ")
newWords = [] # eqivalent to: new ArrayList<String>();
for w in words:
if len(w) > 1:
newWords.append(w[::-1]) # w[::-1] reverses a string in python
else:
newWords.append(w) # append is like ArrayList.add(e)
return "".join(newWords) # this joins a list to a string. In java: String.join("", list);
print(reverse("stack, overflow."))
# output: kcats, wolfrevo.发布于 2019-02-11 20:04:30
使用正则表达式在特殊字符处拆分输入,将这些字符保留在结果数组中;在上面的示例中,在空格char、逗号和点处拆分。然后反转结果数组中的每个元素,并将它们连接到一个新的字符串。示例:
public static void main(String[] args) {
String input = "stack, overflow.";
String[] splited = splitInput(input);
String result = "";
for(String s : splited){
result += reverseString(s);
}
System.out.println(result);
}
public static String[] splitInput(String input) {
// [,\\. ] -> split at , . ' ' and keep the delimiters
// this will produce for the example input [stack, ,, , overflow, .]
String regex = "((?<=[,\\. ])|(?=[,\\. ]))";
return input.split(regex);
}
public static String reverseString(String str) {
return new StringBuilder(str).reverse().toString();
}发布于 2019-02-11 20:08:50
也许您应该考虑在这里使用堆栈数据结构,而不是数组。堆栈有一个FILO方法--您放入的第一个项目是最后一个出来的项目。考虑一下像一堆砖头或薄煎饼这样的东西。第一个放置在底部。
Here is a little driver program to show you what I mean:
import java.io.*;
import java.util.*;
class Test{
public static void main (String[] args){
// creates a stack
Stack<Integer> word_stack = new Stack<Integer>();
// grab user input
Scanner myScan = new Scanner(System.in);
System.out.println("Please input a phrase");
// conver it to an array
String userInput = myScan.nextLine();
char[] userInputArray = userInput.toCharArray();
// pushes everything onto the stack
for (int i = 0; i < userInputArray.length; i++){
word_stack.stack_push(userInputArray[i]);
}
// pops it off
for (i < 0; i < userInputArray.length; i++) {
System.out.println(userInputArray[i]);
word_stack.stack_pop();
} //end for
} //end psvm
} // end classhttps://stackoverflow.com/questions/54629516
复制相似问题