> Java > java지도 시간 > 본문

Java에서 바이트 배열을 사용하여 문자를 뒤집는 방법

WBOY
풀어 주다: 2023-04-29 10:49:06
앞으로
1354명이 탐색했습니다.

바이트 배열 사용

package net.javaguides.corejava.string;
/**
* 
* @author yisu
*
*/
public class ReverseStringUsingByteArray {
// Function to reverse a string in Java using byte array
public static String reverse(String str) {
// return if string is null or empty
if (str == null || str.equals(""))
return str;
// convert string into bytes
byte[] bytes = str.getBytes();
// start from the two end points l and h of the given string
// and increment l & decrement h at each iteration of the loop
// until two end-points intersect (l >= h)
for (int l = 0, h = str.length() - 1; l < h; l++, h--) {
// Swap values at l and h
byte temp = bytes[l];
bytes[l] = bytes[h];
bytes[h] = temp;
}
// convert byte array back into the string
return new String(bytes);
}
public static void main(String[] args) {
String str = "Java Guides";
// String is immutable
str = reverse(str);
System.out.println("Reverse of the given string is : " + str);
}
}
로그인 후 복사

출력:

Reverse of the given string is : sediuG avaJ
로그인 후 복사

위 내용은 Java에서 바이트 배열을 사용하여 문자를 뒤집는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:yisu.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!