Java/Java 기타

자바 모든 스트링 한문자로 바꾸는 3가지 방법

kimc 2022. 2. 10. 19:55

```

자바에서 문자열 한 가지로 바꾸는 3가지 방법

```

이번 글을 통해 배워갈 내용

  1.  문자열을 한 가지 문자로 치환하는 3가지 방법

"ABCD"라는 문자열을 "AAAA" 혹은 한 가지 문자로 변환하고자 한다면

 

자바 11버전 이상은

str = "A".repeat(str.length());

자바 8은

str = str.replaceAll(".", "A");

자바 8 이전은

int len = str.length();
StringBuilder sb = new StringBuilder(len);
for(int i = =; i < len; i++){
    sb.append('A');
}
return sb.toString();

과 같이 진행해주면 됩니다.

모든 문자를 * 로 변환하거나 다른 문자로 변환하고자 하신다면

A를 해당되는 문자로 바꿔서 사용해주시면 됩니다.

 

 

 

 

읽어주셔서 감사합니다

 

무엇인가 얻어가셨기를 바라며

 

오늘도 즐거운 코딩 하시길 바랍니다 ~ :)

 


참조

https://stackoverflow.com/questions/7318359/how-to-replace-all-characters-in-a-java-string-with-stars

 

How to replace all characters in a Java string with stars

I want to replace all the characters in a Java String with * character. So it shouldn't matter what character it is, it should be replaced with a *. I know there are heaps of examples there on int...

stackoverflow.com

 

728x90