I have a string String email="rachitgulati26#gmail.com" so its length is 24.
I want result like rachit************il.com.That means 1/4 of initial same and last 1/4 same.
Just want to convert 1/2 from middle to * with the help of regEX.
Thanks
You could do something like this:
"rachitgulati26#gmail.com".replaceAll("(?<=.{5}).(?=.{5})", "*");
this will replace all characters to * apart from the first and last 5.
In response to your question, you could make this flexible like this:
String email = "rachitgulati26#gmail.com";
int i = email.length() / 4;
email = email.replaceAll("(?<=.{" + i + "}).(?=.{" + i + "})", "*");
Just a word of warning, if you were to start using this in production code, you probably want to create a way of caching these regexes, based on the value of i. This way is for demonstration of the pattern only, and will compile a regex Pattern each time it is used.
One way to do it is to create a string of '*'s that is the correct length, then concatenate on the surrounding parts of the original string. That way you don't have to do any looping:
public static String starize(String str){
char[] middle = new char[str.length()/2];
Arrays.fill(middle, '*');
return str.substring(0, str.length()/4)
+ String.copyValueOf(middle)
+ str.substring(3 * str.length() / 4);
}
You could convert to char array, process and convert back to String:
String email = "rachitgulati26#gmail.com";
char[] a = email.toCharArray();
for (int i = 0, j = a.length >> 2; i < a.length >> 1; i++, j++)
a[j] = '*';
email = new String(a);
Result:
rachit************il.com
You can't identify the middle of a string using a single regular expression unless the lengths have a finite number of values.
Related
I wanted to have a List with Unicode Strings, but I wondered if I could use a for loop instead of adding 9 variables by hand. I tried the following code, but it didn't work.
List<String> reactions = new ArrayList<>();
for (int i = 1; i < 10; i++) {
reactions.add("\u003" + i + "\u20E3");
}
My IDEA gives me an 'illegal unicode escape' error.
Is there an other way to accomplish this?
The easiest way to convert a number to a character within a string is probably using a Formatter, via String.format:
List<String> reactions = new ArrayList<>();
for (int i = 1; i < 10; i++) {
reactions.add(String.format("%c\u20e3", 0x0030 + i));
}
Assuming you want to display the character \u003i, with ifrom 1 to 9, and \u20E3, remember a character is like a number and can be used in mathematical operation.
get the character \u0030: '\u0030'
add i : '\u0030' + i
concatenate the new character with the other one (as a string)
Then print the result:
System.out.println((char)('\u0030' + i) + "\u20E3");
Below Java code produces the valid output but it takes more time to execute. Code works fine in eclipse, but it do not work in an online compiler like hackerrank or hackerearth since it takes more time for execution.Someone help me to find the solution for my time complexity problem.
I have tried to find the solution of the problem but i wasn't able to fix the performance by reducing the time..
Scanner scan = new Scanner(System. in );
String s = "aab";
String s1 = "";
String s2 = "";
int n1 = 0;
int length = 0;
long n = 882787;
long count = 0;
while (s1.length() < n) {
s1 = s1 + s;
}
if (s1.length() > n) {
count = s1.length() - n;
n1 = (int) count;
}
for (int i = 0; i < s1.length() - n1; i++) {
if (s1.charAt(i) == 'a') {
length += 1;
}
}
System.out.println(length);
Explanation of the above program:
I have a string s,in lowercase English letters that .I have repeat the string for n times and I store it in the new string.
I have to find the number of occurrences of 'a' in my new string
How do i actually reduce the time complexity for the above program
Thanks in advance
I would use a regular expression to create a String based on the initial input consisting of only letter 'a'(s). Take the length of that String and multiply it by n. That is one line that looks like
System.out.println(s.replaceAll("[^a]+", "").length() * n);
You are going to add s to the string n/s.length() times, call this N:
int N = n / s.length();
Each time you add s to the string you are going to append the number of As in s:
int a = 0;
for (int i = 0; i < s.length(); ++i) {
a += s.charAt(i) == 'a' ? 1 : 0;
}
// Or int a = s.replaceAll("[^a]", "").length();
So multiple these together:
int length = a * N;
String is immutable. Modification of a string is in fact create a new String object and put both old and new String into Java String constant poom
If you don't want to change your algorithm, I'd suggest to use StringBuilder to improve the speed of the execution. Note that StringBuilder is not thread safe
String s="aab";
int n1 = 0;
StringBuilder sb1 = new StringBuilder();
int length=0;
long n=882787;
long count=0;
while(sb1.length() < n) {
sb1.append(s);
}
if(sb1.length()>n) {
count =sb1.length()-n;
n1=(int)count;
}
for(int i=0;i<sb1.length()- n1;i++) {
if(sb1.charAt(i)=='a') {
length+=1;
}
}
System.out.println(length);
From here
When to use which one :
If a string is going to remain constant throughout the program, then
use String class object because a String object is immutable. If a
string can change (example: lots of logic and operations in the
construction of the string) and will only be accessed from a single
thread, using a StringBuilder is good enough. If a string can change,
and will be accessed from multiple threads, use a StringBuffer because
StringBuffer is synchronous so you have thread-safety.
I see multiple possible optimizations:
a) One pattern that is not that good is creating lots of Strings through repeated string concatenation. Each "s1 = s1 + s;" creates a new instance of String which will be obsolet the next time the command runs (It increases the load, because the String instances will be additional work for the Garbage Collector).
b) Generally: If you find, that your algorithm takes too long, then you should think about a complete new way to solve the issue. So a different solution could be:
- You know the length you want to have (n) and the length of the small string (s1) that you use to create the big string. So you can calculate: How often will the small string be inside the target string? How many characters are left?
==> You can simply check the small string for the character you are looking for. That multiplied by the number how often the small string will be inside the big string is the first result that you get.
==> Now you need to check the substring of the small string that are missing.
Example: n=10, s1="aab", Looking for "a":
So first we check how often the s1 will fit into a new string of n Characters n/length(s1) => 3
So we check how often the "a" is inside "aab" -> 2
First result is 3*2 = 6
But we checked for 3*3 = 9 characters so far, but we want 10 characters. So we need to check n % length(s1) = 1 character of s1 and in this substring ("a"), wie have 1 a, so we have to add 1.
So the result is 7 which we got without building a big string (which is not required at all!)
Just check how many times the char occurs in the original and multiple it by n. Here's a simple way to do so without even using regex:
// take these as function input or w/e
String s = "aab";
String find = "a";
long n = 882787;
int count = s.length() - s.replaceAll(find, "").length();
System.out.println(count * n);
I'd like to count the amount of characters within a string, and cut off any excess characters of the string. I thought of just using a while loop and a char, but I need to pass in a string. I also tried to use the remainder function, but I"m pretty sure it wouldn't work.
So, essentially, a counter for a string and then to limit that string to x amount of characters.
If I were to set the string to a single character, say
String x = "*";
Then implemented a counter in a for loop...
for(int i = 0; i < 6; i++){
???
}
Would that work? I feel like it wouldn't, and that it would just be more effective for me to declare
char x = 'a';
...
I'm trying to make this as vague as possible so that I can take ideas and implement them so it's not like I'm stealing anybody's code for homework, I just need a little help.
String myString = "myString";
int maxLength = 3;
if (myString.length() > maxLength)
myString = myString.substring(0, maxLength);
Result will be "myS"
"I was searching around on the web for a manual code to count the amount of characters within a string, and then to a further extent cut off any excess characters of the string."
Count amount of characters within a string:
int length = stringName.length();
Cutting off extra characters of the string
int maxAmount; //wherever you want to stop
if(length > maxAmount)
{
stringName = stringName.substring(0,stopPoint);
}
How could I split the numbers in the string "542" into individual digits? On my desktop I can split the numbers using String.split("") and it works fine. But when run on Android, I get a NumberFormatException: Invalid int: "".
This is my code:
public void render(int n, SpriteBatch batch) {
String[] numbers = String.valueOf(n).split("");
for(int i = 0; i < numbers.length; i++)
batch.draw(Assets.numbers[0][Integer.valueOf(numbers[i])], pos.x + (50 * i), pos.y);
}
Is there an alternative way?
You can use String.charAt, that will give you a Character. Removing '0' will give you a value from 0 to 9.
public void render(int n, SpriteBatch batch) {
String string = Integer.toString(n);
for(int i = 0; i < string.length(); ++i)
batch.draw(Assets.numbers[0][string.charAt(i) - '0'],
pos.x + (50 * i), pos.y);
}
Your use of String.split("") will always leave the first index empty (that is, the String: ""). This is why you are getting NumberFormatException: Invalid int: "" when trying to run Integer.valueOf(numbers[0]).
Suggest using string.charAt(index) to iterate over the characters in String.valueOf(n) instead.
Splitting on "" will cause the first element of the resulting array to be a blank, because the blank regex matches everywhere, including start of input.
You need to split after every character:
String[] digits = str.split("(?<=.)");
This regex is a look behind that assets there is a character before the match. Look behinds are non-consuming, so you don't lose any input making the split.
public class newString {
public static void main (String args[]){
String title = "Book";
String title1;
title1 = title;
for(int i = 0; i < title.length(); i++){
for (int x = 0; x<title1.length(); x++){
if (title.charAt(i+x) == title1.charAt(x)){
System.out.print(title.charAt(0,1));
}
}
}
}
}
I really don't understand what I'm doing wrong here. What I need to do is define a string called "title", with "Book" in it, which I did, and create a second string called "title1". I need to create code to store the contents of title, into title1, but only every other character. For example: title1 should have "Bo" in it. What am I doing wrong?
Here's the looping solution with fewer operations. Instead of checking if i is even, just increment by 2.
String title1 = "Some title";
String title2 = "";
for (int i = 0; i < title1.length(); i += 2)
{
title2 += title1.charAt(i);
}
You algorithm is wrong, it seems what you need to do is to extract out every nth character from source string, for example:
String source = "Book";
End result should be "Bo"
The algorithm should be:
Iterate through each character in the original string, use a stride as you need, in this case, a stride of 2 should do (so rather than increment by one, increment by the required stride)
Take the character at that index and add it to your second string
The end result should be a string which holds every nth character.
I don't really understand what you are attempting, but I can tell you what you are doing. Your loop structure does the following:
when i = 0, it compares all characters in both strings (0 + n = n, so the inner loop goes from x - title1.length()).
when i = 1, compare all characters except the first one (for size x, 1 + n = x - 1 comparisons).
when i =2, compare x / 2 characters (for size x, 2 + n = x / 2)
when i = 3, compare x / 3 characters
... and so on
System.out.print(title.charAt(0,1)) Shouldn't even compile. charAt(int) is the correct call. And if title length is greater than 0, this will always print a String with a single character -- the first one in title. And it will always be the same unless you reassign title to a different String.
Also this code will always throw an IndexOutOfBoundsException at title.charAt(i+x) when i = title.length() - 1 and x > 0.