How can I read an input string in Java?

王林
Release: 2024-01-25 10:39:12
forward
907 people have browsed it

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!

source:docexcel.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!