How to replace all characters in a Java string with stars - java

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 internet but have not one that replaces every character and I have tried myself but no success.

Java 11 and later
str = "*".repeat(str.length());
Note: This replaces newlines \n with *. If you want to preserve \n, see solution below.
Java 10 and earlier
str = str.replaceAll(".", "*");
This preserves newlines.
To replace newlines with * as well in Java 10 and earlier, you can use:
str = str.replaceAll("(?s).", "*");
The (?s) doesn't match anything but activates DOTALL mode which makes . also match \n.

Don't use regex at all, count the String length, and return the according number of stars.
Plain Java < 8 Version:
int len = str.length();
StringBuilder sb = new StringBuilder(len);
for(int i = =; i < len; i++){
sb.append('*');
}
return sb.toString();
Plain Java >= 8 Version:
int len = str.length();
return IntStream.range(0, n).mapToObj(i -> "*").collect(Collectors.joining());
Using Guava:
return Strings.repeat("*", str.length());
// OR
return CharMatcher.ANY.replaceFrom(str, '*');
Using Commons / Lang:
return StringUtils.repeat("*", str.length());

System.out.println("foobar".replaceAll(".", "*"));

public String allStar(String s) {
StringBuilder sb = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
sb.append('*');
}
return sb.toString();
}

How abt creating a new string with the number of * = number of last string char?
StringBuffer bf = new StringBuffer();
for (int i = 0; i < source.length(); i++ ) {
bf.append('*');
}

There may be other faster/better ways to do it, but you could just use a string buffer and a for-loop:
public String stringToAsterisk(String input) {
if (input == null) return "";
StringBuffer sb = new StringBuffer();
for (int x = 0; x < input.length(); x++) {
sb.append("*");
}
return sb.toString();
}
If your application is single threaded, you can use StringBuilder instead, but it's not thread safe.
I am not sure if this might be any faster:
public String stringToAsterisk(String input) {
if (input == null) return "";
int length = input.length();
char[] chars = new char[length];
while (length > 0) chars[--length] = "*";
return new String(chars);
}

Without any external library and without your own loop, you can do:
String input = "Hello";
char[] ca = new char[input.length()];
Arrays.fill(ca, '*');
String output = new String(ca);
BTW, both Arrays.fill() and String(char []) are really fast.

Recursive method
String nCopies(String s, int n) {
return n == 1 ? s.replaceFirst(".$", "") : nCopies(s + s, --n);
}

String text = "Hello World";
System.out.println( text.replaceAll( "[A-Za-z0-9]", "*" ) );
output : ***** *****

Related

Censor word from a string [duplicate]

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 internet but have not one that replaces every character and I have tried myself but no success.
Java 11 and later
str = "*".repeat(str.length());
Note: This replaces newlines \n with *. If you want to preserve \n, see solution below.
Java 10 and earlier
str = str.replaceAll(".", "*");
This preserves newlines.
To replace newlines with * as well in Java 10 and earlier, you can use:
str = str.replaceAll("(?s).", "*");
The (?s) doesn't match anything but activates DOTALL mode which makes . also match \n.
Don't use regex at all, count the String length, and return the according number of stars.
Plain Java < 8 Version:
int len = str.length();
StringBuilder sb = new StringBuilder(len);
for(int i = =; i < len; i++){
sb.append('*');
}
return sb.toString();
Plain Java >= 8 Version:
int len = str.length();
return IntStream.range(0, n).mapToObj(i -> "*").collect(Collectors.joining());
Using Guava:
return Strings.repeat("*", str.length());
// OR
return CharMatcher.ANY.replaceFrom(str, '*');
Using Commons / Lang:
return StringUtils.repeat("*", str.length());
System.out.println("foobar".replaceAll(".", "*"));
public String allStar(String s) {
StringBuilder sb = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
sb.append('*');
}
return sb.toString();
}
How abt creating a new string with the number of * = number of last string char?
StringBuffer bf = new StringBuffer();
for (int i = 0; i < source.length(); i++ ) {
bf.append('*');
}
There may be other faster/better ways to do it, but you could just use a string buffer and a for-loop:
public String stringToAsterisk(String input) {
if (input == null) return "";
StringBuffer sb = new StringBuffer();
for (int x = 0; x < input.length(); x++) {
sb.append("*");
}
return sb.toString();
}
If your application is single threaded, you can use StringBuilder instead, but it's not thread safe.
I am not sure if this might be any faster:
public String stringToAsterisk(String input) {
if (input == null) return "";
int length = input.length();
char[] chars = new char[length];
while (length > 0) chars[--length] = "*";
return new String(chars);
}
Without any external library and without your own loop, you can do:
String input = "Hello";
char[] ca = new char[input.length()];
Arrays.fill(ca, '*');
String output = new String(ca);
BTW, both Arrays.fill() and String(char []) are really fast.
Recursive method
String nCopies(String s, int n) {
return n == 1 ? s.replaceFirst(".$", "") : nCopies(s + s, --n);
}
String text = "Hello World";
System.out.println( text.replaceAll( "[A-Za-z0-9]", "*" ) );
output : ***** *****

String message divide 10 character by character

I want to divide the following message by 10 character. I want to append every part into StringBuilder object.
04421,1,13,S,312|4000004130,1;4000000491,1;4000005240,1;4000005789,2;4000004978,2;4000004934,2;4000004936,1;4000000569,2;4000005400,1;4000000;4000004934,2;
I have done the following solution :
if(getMsgOtherPart(message) != null){
System.out.println("part message::"+getMsgOtherPart(message));
String newMessage = getMsgOtherPart(message) ;
int len = newMessage.length();
System.out.println("len::"+len);
int firstIndex = 0;
int limit = 10;
int lastIndex = 10;
int count = 0;
StringBuilder sb = new StringBuilder();
String completeMessage = null;
for(int i = 0; i <= len;i++){
count++;
if( count == limit && lastIndex < len){
sb.append(getSmsUniqueHeader());
sb.append(newMessage.substring(firstIndex,lastIndex));
sb.append("#");
sb.append("\n");
firstIndex = lastIndex;
lastIndex = firstIndex + limit;
count = 0;
} else if(count < limit && i == len) {
System.out.println("lastIndex:: "+lastIndex);
sb.append(getSmsUniqueHeader());
sb.append(newMessage.substring(lastIndex-10));
sb.append("#");
}
}
completeMessage = sb.toString();
System.out.println("message::\n"+completeMessage);
}
I am getting output:
message::
$04421,1,13#
$,S,312|400#
$0004130,1;#
$4000000491#
$;400000540#
$0,1;400000#
$0;40000000#
$63,1;40000#
$00076,1;40#
$00000776,2#
$;400000078#
$8,2;400000#
------------
$0;#
Please let me know to optimize my solution.
I had done this kind of thing in one of my project and here is the function i used, which return the List but you can modify it and use StringBuilder.
public List<String> splitStringEqually(String txtStr, int subStringSize) {
List<String> splittedStringList = new ArrayList<String>();
for (int start = 0; start < txtStr.length(); start += subStringSize) {
splittedStringList.add(txtStr.substring(start, Math.min(txtStr.length(), start + subStringSize)));
}
return splittedStringList;
}
You can use Google's Guava library and use the Splitter class for this.
StringBuilder sb=new StringBuilder();
for(String s: Splitter.fixedLength(10).split(message)){
sb.append(s);
sb.append("#\n");
}
System.out.println(sb.toString());
String is maintained as char array internally. You can get the copy of that char array using message.toCharArray() and using a simple loop or java 8 streams pick elements in chunks of 10 and do whatever stuff you need to do.
Basing heavily on Rajen Raiyarela's answer and addressing the specific request from the OP, the code may look like this (upvote that one, not this one please!):
public String splitStringEqually(String txtStr, int subStringSize) {
// Start off with the header
StringBuilder sb = new StringBuilder("message::\n");
int len = txtStr.length();
for (int start = 0; start < len; start += subStringSize) {
sb.append("$");
// Copy the next 10 characters, or less if at end of string
// Does not use txtStr.substring() as that creates an
// unnecessary temporary string
sb.append(txtStr, start, Math.min(len, start + subStringSize));
sb.append("#\n");
}
return sb.toString();
}
This can be called with simply:
String completeMessage = splitStringEqually(newMessage, limit);

Java - make new string based on old one and lag

I need to get a new string based on an old one and a lag. Basically, I have a string with the alphabet (s = "abc...xyz") and based on a lag (i.e. 3), the new string should replace the characters in a string I type with the character placed some positions forward (lag). If, let's say, I type "cde" as my string, the output should be "fgh". If any other character is added in the string (apart from space - " "), it should be removed. Here is what I tried, but it doesn't work :
String code = "abcdefghijklmnopqrstuvwxyzabcd"; //my lag is 4 and I added the first 4 characters to
char old; //avoid OutOfRange issues
char nou;
for (int i = 0; i < code.length() - lag; ++i)
{
old = code.charAt(i);
//System.out.print(old + " ");
nou = code.charAt(i + lag);
//System.out.println(nou + " ");
// if (s.indexOf(old) != 0)
// {
s = s.replace(old, nou);
// }
}
I commented the outputs for old and nou (new, but is reserved word) because I have used them only to test if the code from position i to i + lag is working (and it is), but if I uncomment the if statement, it doesn't do anything and I leave it like this, it keeps executing the instructions inside the for statmement for code.length() times, but my string doesn't need to be so long. I have also tried to make the for statement like below, but I got lost.
for (int i = 0; i < s.length(); ++i)
{
....
}
Could you help me with this? Or maybe some advices about how I should think the algorithm?
Thanks!
It doesn't work because, as the javadoc of replace() says:
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
(emphasis mine)
So, the first time you meet an 'a' in the string, you replace all the 'a's by 'd'. But then you go to the next char, and if it's a 'd' that was an 'a' before, you replace it once again, etc. etc.
You shouldn't use replace() at all. Instead, you should simply build a new string, using a StringBuilder, by appending each shifted character of the original string:
String dictionary = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder(input.length());
for (int i = 0; i < input.length(); i++) {
char oldChar = input.charAt(i);
int oldCharPositionInDictionary = dictionary.indexOf(oldChar);
if (oldCharPositionInDictionary >= 0) {
int newCharPositionInDictionary =
(oldCharPositionInDictionary + lag) % dictionary.length();
sb.append(dictionary.charAt(newCharPositionInDictionary));
}
else if (oldChar == ' ') {
sb.append(' ');
}
}
String result = sb.toString();
Try this:
Convert the string to char array.
iterate over each char array and change the char by adding lag
create new String just once (instead of loop) with new String passing char array.
String code = "abcdefghijklmnopqrstuvwxyzabcd";
String s = "abcdef";
char[] ch = s.toCharArray();
char[] codes = code.toCharArray();
for (int i = 0; i < ch.length; ++i)
{
ch[i] = codes[ch[i] - 'a' + 3];
}
String str = new String(ch);
System.out.println(str);
}
My answer is something like this.
It returns one more index to every character.
It reverses every String.
Have a good day!
package org.owls.sof;
import java.util.Scanner;
public class Main {
private static final String CODE = "abcdefghijklmnopqrstuvwxyz"; //my lag is 4 and I added the first 4 characters to
#SuppressWarnings("resource")
public static void main(String[] args) {
System.out.print("insert alphabet >> ");
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
char[] char_arr = s.toCharArray();
for(int i = 0; i < char_arr.length; i++){
int order = CODE.indexOf(char_arr[i]) + 1;
if(order%CODE.length() == 0){
char_arr[i] = CODE.charAt(0);
}else{
char_arr[i] = CODE.charAt(order);
}
}
System.out.println(new String(char_arr));
//reverse
System.out.println(reverse(new String(char_arr)));
}
private static String reverse (String str) {
char[] char_arr = str.toCharArray();
for(int i = 0; i < char_arr.length/2; i++){
char tmp = char_arr[i];
char_arr[i] = char_arr[char_arr.length - i - 1];
char_arr[char_arr.length - i - 1] = tmp;
}
return new String(char_arr);
}
}
String alpha = "abcdefghijklmnopqrstuvwxyzabcd"; // alphabet
int N = alpha.length();
int lag = 3; // shift value
String s = "cde"; // input
StringBuilder sb = new StringBuilder();
for (int i = 0, index; i < s.length(); i++) {
index = s.charAt(i) - 'a';
sb.append(alpha.charAt((index + lag) % N));
}
String op = sb.toString(); // output

Getting String from StringBuilder

I was working with StringBuilder to eliminate some unnecessary chars, I got some strange result.
String value = "1.045,00";
StringBuilder sanitized = new StringBuilder();
boolean decimalSeparatorFound = false;
char[] chars = value.toCharArray();
for (int i = chars.length-1; i >= 0; i--) {
if (chars[i] == ',' || chars[i] == '.') {
if (decimalSeparatorFound) continue; // skip this char
decimalSeparatorFound = true;
sanitized.append('.');
} else {
sanitized.append(chars[i]);
}
}
here I will get 00.5401 as a result in sanitized but when I was converting it to string like
String s = sanitized.reverse.toString();
and It is expected to print the value of s as 1045.00 but it get printed as 00.5401.
then I tried it as
StringBuilder sb = sanitized.reverse();
String s1 = sb.toString();
now this time it got printed correctly.
here my question why the StringBuilder is behaving this way? Isn't it performing reverse operation while assigning the value to String s?
"my question why the StringBuilder is behaving this way?"
What's happening is that if you have both ways in the same code, it will reverse once, then reverse again
StringBuilder sb = sanitized.reverse(); // first reverse
String s1 = sb.toString();
String s = sanitized.reverse().toString(); // second reverse
System.out.println(s1);
System.out.println(s);
OUTPUT
1045.00
00.5401
But if you take out the first reverse and just use the second reverse by itself, you get the correct output
String s = sanitized.reverse().toString();
System.out.println(s);
OUPUT
1045.00
Change append to insert
sanitized.insert(0, '.');
} else {
sanitized.insert(0, chars[i]);
}
I would do it simpler
String decimalSeparator = s.indexOf(',') > s.indexOf('.') ? "." : ",";
s = s.replace(decimalSeparator, "");
In this loop, You are reversing the string by appending to StringBuilder from chars[chars.length-1] to chars[0]
for (int i = chars.length-1; i >= 0; i--) {
if (chars[i] == ',' || chars[i] == '.') {
if (decimalSeparatorFound) continue; // skip this char
decimalSeparatorFound = true;
sanitized.append('.');
} else {
sanitized.append(chars[i]);
}
}
This is the actual reason for the reversion. You should change the loop like this
for (int i = 0; i < chars.length; i++) {
if (chars[i] == ',' || chars[i] == '.') {
if (decimalSeparatorFound) continue; // skip this char
decimalSeparatorFound = true;
sanitized.append('.');
} else {
sanitized.append(chars[i]);
}
}
So, it will work as you expect
Can you please try this:
Use StringBuilder's or StringBuffer's method... reverse()
public class StringReverse
{
public static void main(String[] args)
{
String string=args[0];
String reverse = new StringBuilder(string).reverse().toString();
System.out.println("\nString before reverse: "+string);
System.out.println("String after reverse: "+reverse);
}
}
StringBuffer is thread-safe, where as StringBuilder is Not thread safe.....
StringBuilder was introduced from Java 1.5, as to do those operations faster which doesn't have any Concurrency to worry about....
Hope this helps..
You didn't call reverse method in the right way.
You should call it reverse() with braces.
Your line should be like this:
// now they will give you the same results
String s1 = sanitized.reverse().toString();
System.out.println(s1) //1045.00
StringBuilder sb = sanitized.reverse();
String s1 = sb.toString();
System.out.println(s1) //1045.00
Instead of doing this
for (int i = chars.length-1; i >= 0; i--)
you should try this
for (int i = 0; i <chars.length; i++)
May be you are using reverse two times.

Add spaces between the characters of a string in Java?

I just want to add a space between each character of a string. Can anyone help me figuring out how to do this?
E.g. given "JAYARAM", I need "J A Y A R A M" as the result.
Unless you want to loop through the string and do it "manually" you could solve it like this:
yourString.replace("", " ").trim()
This replaces all "empty substrings" with a space, and then trims off the leading / trailing spaces.
ideone.com demonstration
An alternative solution using regular expressions:
yourString.replaceAll(".(?=.)", "$0 ")
Basically it says "Replace all characters (except the last one) with with the character itself followed by a space".
ideone.com demonstration
Documentation of...
String.replaceAll (including the $0 syntax)
The positive look ahead (i.e., the (?=.) syntax)
StringBuilder result = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
if (i > 0) {
result.append(" ");
}
result.append(input.charAt(i));
}
System.out.println(result.toString());
Iterate over the characters of the String and while storing in a new array/string you can append one space before appending each character.
Something like this :
StringBuilder result = new StringBuilder();
for(int i = 0 ; i < str.length(); i++)
{
result = result.append(str.charAt(i));
if(i == str.length()-1)
break;
result = result.append(' ');
}
return (result.toString());
Blow up your String into array of chars, loop over the char array and create a new string by succeeding a char by a space.
Create a StringBuilder with the string and use one of its insert overloaded method:
StringBuilder sb = new StringBuilder("JAYARAM");
for (int i=1; i<sb.length(); i+=2)
sb.insert(i, ' ');
System.out.println(sb.toString());
The above prints:
J A Y A R A M
This would work for inserting any character any particular position in your String.
public static String insertCharacterForEveryNDistance(int distance, String original, char c){
StringBuilder sb = new StringBuilder();
char[] charArrayOfOriginal = original.toCharArray();
for(int ch = 0 ; ch < charArrayOfOriginal.length ; ch++){
if(ch % distance == 0)
sb.append(c).append(charArrayOfOriginal[ch]);
else
sb.append(charArrayOfOriginal[ch]);
}
return sb.toString();
}
Then call it like this
String result = InsertSpaces.insertCharacterForEveryNDistance(1, "5434567845678965", ' ');
System.out.println(result);
I am creating a java method for this purpose with dynamic character
public String insertSpace(String myString,int indexno,char myChar){
myString=myString.substring(0, indexno)+ myChar+myString.substring(indexno);
System.out.println(myString);
return myString;
}
This is the same problem as joining together an array with commas. This version correctly produces spaces only between characters, and avoids an unnecessary branch within the loop:
String input = "Hello";
StringBuilder result = new StringBuilder();
if (input.length() > 0) {
result.append(input.charAt(0));
for (int i = 1; i < input.length(); i++) {
result.append(" ");
result.append(input.charAt(i));
}
}
public static void main(String[] args) {
String name = "Harendra";
System.out.println(String.valueOf(name).replaceAll(".(?!$)", "$0 "));
System.out.println(String.valueOf(name).replaceAll(".", "$0 "));
}
This gives output as following use any of the above:
H a r e n d r a
H a r e n d r a
One can use streams with java 8:
String input = "JAYARAM";
input.toString().chars()
.mapToObj(c -> (char) c + " ")
.collect(Collectors.joining())
.trim();
// result: J A Y A R A M
A simple way can be to split the string on each character and join the parts using space as the delimiter.
Demo:
public class Main {
public static void main(String[] args) {
String s = "JAYARAM";
s = String.join(" ", s.split(""));
System.out.println(s);
}
}
Output:
J A Y A R A M
ONLINE DEMO
Create a char array from your string
Loop through the array, adding a space +" " after each item in the array(except the last one, maybe)
BOOM...done!!
If you use a stringbuilder, it would be efficient to initalize the length when you create the object. Length is going to be 2*lengthofString-1.
Or creating a char array and converting it back to the string would yield the same result.
Aand when you write some code please be sure that you write a few test cases as well, it will make your solution complete.
I believe what he was looking for was mime code carrier return type code such as %0D%0A (for a Return or line break)
and
\u00A0 (for spacing)
or alternatively
$#032

Categories

Resources