温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java如何使用堆栈反转字符

发布时间:2022-03-31 14:57:01 来源:亿速云 阅读:170 作者:小新 栏目:大数据

这篇文章给大家分享的是有关java如何使用堆栈反转字符的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

使用堆栈

package net.javaguides.corejava.string;
import java.util.Stack;
/**
* 
* @author Ramesh Fadatare
*
*/
public class ReverseStringUsingStack {
// Function to reverse a string in Java using a stack and character array
public static String reverse(String str) {
// base case: if string is null or empty
if (str == null || str.equals(""))
return str;
// create an empty stack of characters
Stack < Character > stack = new Stack < Character > ();
// push every character of the given string into the stack
char[] ch = str.toCharArray();
for (int i = 0; i < str.length(); i++)
stack.push(ch[i]);
// start from index 0
int k = 0;
// pop characters from the stack until it is empty
while (!stack.isEmpty()) {
// assign each popped character back to the character array
ch[k++] = stack.pop();
}
// convert the character array into string and return it
return String.copyValueOf(ch);
}
public static void main(String[] args) {
String str = "javaguides";
str = reverse(str); // string is immutable
System.out.println("Reverse of the given string is : " + str);
}
}

输出:

Reverse of the given string is : sediugavaj

java基本数据类型有哪些

Java的基本数据类型分为:1、整数类型,用来表示整数的数据类型。2、浮点类型,用来表示小数的数据类型。3、字符类型,字符类型的关键字是“char”。4、布尔类型,是表示逻辑值的基本数据类型。

感谢各位的阅读!关于“java如何使用堆栈反转字符”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI