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
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);
how can I modify my code so that it removes all the characters in a given string (not just a string) in another string in O(n)? If using other data structures would help, please hint as well.
public static String removeChar(String s, char ch){
StringBuilder sb= new StringBuilder();
char[] charArray= s.toCharArray();
for (int i=0; i<charArray.length; i++){
if (charArray[i]!=ch) {
sb.append(charArray[i]);
}
}
return sb.toString();
}
Is there a faster way for this?
UPDATE: I want to write a new function like removeAllCharsInSecondStringFromFirstString(String S1, String S2)
Rather then iterating each character of the String, you could use String.indexOf(int) and a loop to add each substring between ch intervals. Something like,
public static String removeChar(String s, char ch) {
StringBuilder sb = new StringBuilder();
int p1 = 0, p2 = s.indexOf(ch);
while (p2 > -1) {
sb.append(s.substring(p1, p2));
p1 = p2 + 1;
p2 = s.indexOf(ch, p1);
}
if (p1 < s.length()) {
sb.append(s.substring(p1, s.length()));
}
return sb.toString();
}
With hints and help of dimo I wrote this solution:
public static String removeAllChars(String src, String dst){
HashSet<Character> chars = new HashSet<>();
char[] dstCharArray=dst.toCharArray();
for (int i=0; i<dstCharArray.length; i++){
chars.add(dstCharArray[i]);
}
StringBuilder sb = new StringBuilder();
char[] srcCharArray = src.toCharArray();
for (int i=0; i<srcCharArray.length; i++){
if (!chars.contains(srcCharArray[i])){
sb.append(srcCharArray[i]);
}
}
return sb.toString();
}
If you really want to implement this yourself you can use a Set to contain the collection of characters that you want to strip out. Here's a template to get you started:
public static String removeAllChars(String source, String charsString) {
HashSet<Character> chars = new HashSet<>();
for (int i = 0; i < charsString.length(); i++) {
chars.add(charsString.charAt(i));
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < source.length(); i++) {
// chars.contains(source.charAt(i)) is O(1)
// use this to determine which chars to exclude
}
return sb.toString();
}
Try to use this.
Remove all no numerical value
String str = "343.dfsdgdffsggdfg333";
str = str.replaceAll("[^\\d.]", "");
Output will give you "343.333"
If in the future you will need delete numerical and special value try this
String str = "343.dfsdgdffsggdfg333";
string = string.replace(/[^a-zA-Z0-9]/g, '');
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
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.
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 : ***** *****