Home  >  Article  >  Computer Tutorials  >  How can I read an input string in Java?

How can I read an input string in Java?

王林
王林forward
2024-01-25 10:39:12958browse

How can I read an input string in Java?

In the java language, I enter a string: How can I use abc in the simplest way

I wrote a more general method, which is not limited to 3 characters, and can be of any length. It can be used for communication:

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner input = new Scanner(System.in);

System.out.println("Please enter a string:");

String str = input.next();

Reverse(str);

}

public static void Reverse(String str){

System.out.println ("The reversed string is:");

for(int i = 0; i String temp = """;

temp = temp str.charAt(str.length()-i-1);

System.out.print(temp);

}

Java implements string reversal to optimize time and space complexity

I don’t know why you have this idea. If you have a good algorithm, you can discuss it with me. I wrote 2 codes below hoping to help you.

package app;

public class TransDemo {

//abcdef" is reversed to "fedcba

public static void main(String[] args){

String str = "abcdef";

char[] ary = str.toCharArray();

for(int i = 0; i

int temp = ary[ary.length-i-1]-ary[i];

ary[i] = temp;

ary[ary.length-i-1] -=temp;

}

str = new String(ary);

System.out.println(str);

}

}

package app;

public class TransDemo {

//abcdef" is reversed to "fedcba

public static void main(String[] args){

String str = "abcdef";

char[] ary = str.toCharArray();

for(int i = 0; i

char c = ary[i];

ary[i] = ary[str.length()-1-i];

ary[str.length()-1-i] = c;

}

str = new String(ary);

System.out.println(str);

}

}

The above is the detailed content of How can I read an input string in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:docexcel.net. If there is any infringement, please contact admin@php.cn delete