Java 字反转
Java words reverse
我是 Java 的新手,我发现了一个我想解决的有趣问题。我正在尝试编写一个程序来反转字符串中每个单词的位置。例如,输入字符串 = "HERE AM I",输出字符串将为 "I AM HERE"。我已经进入它,但它不适合我。任何人都可以指出错误以及如何解决它,因为我真的很想知道出了什么问题。谢谢!
import java.util.Scanner;
public class Count{
static Scanner sc = new Scanner(System.in);
static String in = ""; static String ar[];
void accept(){
System.out.println("Enter the string: ");
in = sc.nextLine();
}
void intArray(int words){
ar = new String[words];
}
static int Words(String in){
in = in.trim(); //Rm space
int wc = 1;
char c;
for (int i = 0; i<in.length()-1;i++){
if (in.charAt(i)==' '&&in.charAt(i+1)!=' ') wc++;
}
return wc;
}
void generate(){
char c; String w = ""; int n = 0;
for (int i = 0; i<in.length(); i++){
c = in.charAt(i);
if (c!=' '){
w += c;
}
else {
ar[n] = w; n++;
}
}
}
void printOut(){
String finale = "";
for (int i = ar.length-1; i>=0;i--){
finale = finale + (ar[i]);
}
System.out.println("Reversed words: " + finale);
}
public static void main(String[] args){
Count a = new Count();
a.accept();
int words = Words(in);
a.intArray(words);
a.generate();
a.printOut();
}
}
我会使用拆分功能,然后从列表的末尾打印到前面。
String[] splitString = str.split(" ");
for(int i = splitString.length() - 1; i >= 0; i--){
System.out.print(splitString[i]);
if(i != 0) System.out.print(' ');
}
糟糕,请阅读您的评论。如果这不是你想要的,请忽略它。
通过在每个方法调用之间添加调试输出,很容易确定您是否成功读取输入、计算单词数和初始化数组。这意味着问题出在 generate()
.
generate()
中的问题 1(为什么 "HERE" 在输出中重复):将 w
添加到数组后(当单词完成时)您不重置w
到 ""
,这意味着每个单词前面都有前面的单词。通过添加调试输出(或使用调试器)打印 ar
和 w
循环的每次迭代的状态,这很容易看出。
generate()
中的问题2(为什么"I"不在输出中):字符串中没有尾随space,所以添加单词的条件在循环终止于字符串末尾之前,数组永远不会满足最后一个单词的要求。简单的解决方法是在循环结束后添加 ar[n] = w;
以覆盖最后一个单词。
知道了。这是我从 scratch 实现 split
和 reverse
的代码。
split 函数是通过遍历字符串并跟踪开始和结束索引来实现的。一旦字符串中的一个索引等于“”,程序将结束索引设置为 space 后面的元素,并将前一个子字符串添加到 ArrayList
,然后创建一个新的开始索引开头。
Reverse 非常简单 - 您只需从字符串的末尾迭代到字符串的第一个元素。
示例:
Input: df gf sd
Output: sd gf df
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Count{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter string to reverse: ");
String unreversed = scan.nextLine();
System.out.println("Reversed String: " + reverse(unreversed));
}
public static String reverse(String unreversed)
{
ArrayList<String> parts = new ArrayList<String>();
String reversed = "";
int start = 0;
int end = 0;
for (int i = 0; i < unreversed.length(); i++)
{
if (unreversed.charAt(i) == ' ')
{
end = i;
parts.add(unreversed.substring(start, end));
start = i + 1;
}
}
parts.add(unreversed.substring(start, unreversed.length()));
for (int i = parts.size()-1; i >= 0; i--)
{
reversed += parts.get(i);
reversed += " ";
}
return reversed;
}
}
这有一个与拆分功能相同的功能,但不是预定义的拆分功能
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string : ");
String input = sc.nextLine();
// This splits the string into array of words separated with " "
String arr[] = myOwnSplit(input.trim(), ' '); // ["I", "AM", "HERE"]
// This ll contain the reverse string
String rev = "";
// Reading the array from the back
for(int i = (arr.length - 1) ; i >= 0 ; i --) {
// putting the words into the reverse string with a space to it's end
rev += (arr[i] + " ");
}
// Getting rid of the last extra space
rev.trim();
System.out.println("The reverse of the given string is : " + rev);
}
// The is my own version of the split function
public static String[] myOwnSplit(String str, char regex) {
char[] arr = str.toCharArray();
ArrayList<String> spltedArrayList = new ArrayList<String>();
String word = "";
// splitting the string based on the regex and bulding an arraylist
for(int i = 0 ; i < arr.length ; i ++) {
char c = arr[i];
if(c == regex) {
spltedArrayList.add(word);
word = "";
} else {
word += c;
}
if(i == (arr.length - 1)) {
spltedArrayList.add(word);
}
}
String[] splitedArray = new String[spltedArrayList.size()];
// Converting the arraylist to string array
for(int i = 0 ; i < spltedArrayList.size() ; i++) {
splitedArray[i] = spltedArrayList.get(i);
}
return splitedArray;
}
这是我的建议:
String s = " HERE AM I ";
s = s.trim();
int j = s.length() - 1;
int index = 0;
StringBuilder builder = new StringBuilder();
for (int i = j; i >= 0; i--) {
Character c = s.charAt(i);
if (c.isWhitespace(c)) {
index = i;
String r = s.substring(index+1, j+1);
j = index - 1;
builder.append(r);
builder.append(" ");
}
}
String r=s.substring(0, index);
builder.append(r);
System.out.println(builder.toString());
我是 Java 的新手,我发现了一个我想解决的有趣问题。我正在尝试编写一个程序来反转字符串中每个单词的位置。例如,输入字符串 = "HERE AM I",输出字符串将为 "I AM HERE"。我已经进入它,但它不适合我。任何人都可以指出错误以及如何解决它,因为我真的很想知道出了什么问题。谢谢!
import java.util.Scanner;
public class Count{
static Scanner sc = new Scanner(System.in);
static String in = ""; static String ar[];
void accept(){
System.out.println("Enter the string: ");
in = sc.nextLine();
}
void intArray(int words){
ar = new String[words];
}
static int Words(String in){
in = in.trim(); //Rm space
int wc = 1;
char c;
for (int i = 0; i<in.length()-1;i++){
if (in.charAt(i)==' '&&in.charAt(i+1)!=' ') wc++;
}
return wc;
}
void generate(){
char c; String w = ""; int n = 0;
for (int i = 0; i<in.length(); i++){
c = in.charAt(i);
if (c!=' '){
w += c;
}
else {
ar[n] = w; n++;
}
}
}
void printOut(){
String finale = "";
for (int i = ar.length-1; i>=0;i--){
finale = finale + (ar[i]);
}
System.out.println("Reversed words: " + finale);
}
public static void main(String[] args){
Count a = new Count();
a.accept();
int words = Words(in);
a.intArray(words);
a.generate();
a.printOut();
}
}
我会使用拆分功能,然后从列表的末尾打印到前面。
String[] splitString = str.split(" ");
for(int i = splitString.length() - 1; i >= 0; i--){
System.out.print(splitString[i]);
if(i != 0) System.out.print(' ');
}
糟糕,请阅读您的评论。如果这不是你想要的,请忽略它。
通过在每个方法调用之间添加调试输出,很容易确定您是否成功读取输入、计算单词数和初始化数组。这意味着问题出在 generate()
.
generate()
中的问题 1(为什么 "HERE" 在输出中重复):将 w
添加到数组后(当单词完成时)您不重置w
到 ""
,这意味着每个单词前面都有前面的单词。通过添加调试输出(或使用调试器)打印 ar
和 w
循环的每次迭代的状态,这很容易看出。
generate()
中的问题2(为什么"I"不在输出中):字符串中没有尾随space,所以添加单词的条件在循环终止于字符串末尾之前,数组永远不会满足最后一个单词的要求。简单的解决方法是在循环结束后添加 ar[n] = w;
以覆盖最后一个单词。
知道了。这是我从 scratch 实现 split
和 reverse
的代码。
split 函数是通过遍历字符串并跟踪开始和结束索引来实现的。一旦字符串中的一个索引等于“”,程序将结束索引设置为 space 后面的元素,并将前一个子字符串添加到 ArrayList
,然后创建一个新的开始索引开头。
Reverse 非常简单 - 您只需从字符串的末尾迭代到字符串的第一个元素。
示例:
Input: df gf sd
Output: sd gf df
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Count{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter string to reverse: ");
String unreversed = scan.nextLine();
System.out.println("Reversed String: " + reverse(unreversed));
}
public static String reverse(String unreversed)
{
ArrayList<String> parts = new ArrayList<String>();
String reversed = "";
int start = 0;
int end = 0;
for (int i = 0; i < unreversed.length(); i++)
{
if (unreversed.charAt(i) == ' ')
{
end = i;
parts.add(unreversed.substring(start, end));
start = i + 1;
}
}
parts.add(unreversed.substring(start, unreversed.length()));
for (int i = parts.size()-1; i >= 0; i--)
{
reversed += parts.get(i);
reversed += " ";
}
return reversed;
}
}
这有一个与拆分功能相同的功能,但不是预定义的拆分功能
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string : ");
String input = sc.nextLine();
// This splits the string into array of words separated with " "
String arr[] = myOwnSplit(input.trim(), ' '); // ["I", "AM", "HERE"]
// This ll contain the reverse string
String rev = "";
// Reading the array from the back
for(int i = (arr.length - 1) ; i >= 0 ; i --) {
// putting the words into the reverse string with a space to it's end
rev += (arr[i] + " ");
}
// Getting rid of the last extra space
rev.trim();
System.out.println("The reverse of the given string is : " + rev);
}
// The is my own version of the split function
public static String[] myOwnSplit(String str, char regex) {
char[] arr = str.toCharArray();
ArrayList<String> spltedArrayList = new ArrayList<String>();
String word = "";
// splitting the string based on the regex and bulding an arraylist
for(int i = 0 ; i < arr.length ; i ++) {
char c = arr[i];
if(c == regex) {
spltedArrayList.add(word);
word = "";
} else {
word += c;
}
if(i == (arr.length - 1)) {
spltedArrayList.add(word);
}
}
String[] splitedArray = new String[spltedArrayList.size()];
// Converting the arraylist to string array
for(int i = 0 ; i < spltedArrayList.size() ; i++) {
splitedArray[i] = spltedArrayList.get(i);
}
return splitedArray;
}
这是我的建议:
String s = " HERE AM I ";
s = s.trim();
int j = s.length() - 1;
int index = 0;
StringBuilder builder = new StringBuilder();
for (int i = j; i >= 0; i--) {
Character c = s.charAt(i);
if (c.isWhitespace(c)) {
index = i;
String r = s.substring(index+1, j+1);
j = index - 1;
builder.append(r);
builder.append(" ");
}
}
String r=s.substring(0, index);
builder.append(r);
System.out.println(builder.toString());