I want to initialize a string as follows:
public int function ( int count ) {
String s_new = "88888... 'count' number of 8's " <-- How to do this
//Other code
}
Currently I'm not sure how to do this, so I've declared an int array ( int[] s_new ) instead and Im using for loops to initialize this int array.
EDIT: I meant that I need to initialize a string containing only 8's ... the number of times the digit 8 occurs is 'count' times.
You can use Guava's Strings.repeat() method:
String str = Strings.repeat("8", count);
In these cases, it is recommended to use a StringBuilder:
StringBuilder sb = new StringBuilder();
String s = "";
int count = 8;
for (int i = 0; i < count; i++) {
sb.append('8');
}
s = sb.toString();
System.out.println(s);
Output:
88888888
Try:
String s_new = "";
for (int i = 0; i < count; i++) {
s_new += "8";
}
return s_new;
Now, this is a naive solution. A better solution (as is posted in other answers here) will use a StringBuffer or StringBuilder to accomplish this in a more efficient manner.
Also, further reading on the difference between those two options: Difference between StringBuilder and StringBuffer
You can build strings using the StringBuilder class.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++)
sb.append('8')
String s_new = sb.toString();
s_new would then have as much 8 as you have count.
Solution on pure Java using arrays:
public String repeat(char ch, int count) {
char[] chars = new char[count];
Arrays.fill(chars, ch);
return new String(chars);
}
Related
I know that it exists, but my teacher wants me to do it manuallyI am trying to reverse my a stringBuilder so that the characters I have inside go in reverse order, sometimes the stringBuilder is of a single character, that is why as you can see there is an if that indicates when the characters of the stringBuilder should be turned over. This is what I have at the moment.
if ( sB.length ()> 1) {
for (int i = sB.length () - 1; i> = 0; i--) {
sB.append().charAt(i);
sB.deleteCharAt (i);
}
}
I know sB.reverse() exists, but my teacher wants me to do it manually and how you can see i don't know how to implement this two method's at once. If anyone can help me please. Thanks!
then in that case use this
StringBuilder str = new StringBuilder();
str.append("yourstring");
for(int i = str.length()-1 ; i>=0; i--)
{
str.append(str.charAt(i)).deleteCharAt(i);
}
if you want to reverse your string why dont you use
StringBuilder str = new StringBuilder();
str.append("yourstring");
str.reverse();
swap it two by two if you arent allowed to use reverse() method
StringBuilder sb = new StringBuilder("abcde");
for (int i = 0; i < sb.length()/2; i++) {
char tmp = sb.charAt(i);
sb.setCharAt(i, sb.charAt(sb.length() - 1 - i));
sb.setCharAt(sb.length() - 1 - i, tmp);
}
System.out.println(sb.toString());
Use this code to do it manually.
public class Reverse {
public static void main(String args []) {
String rev = "This should be reversed";
StringBuilder stb = new StringBuilder();
int i = rev.length()-1;
while (i != -1) {
char re = rev.charAt(i);
stb.append(re);
i--;
}
System.out.println(stb);
}
}
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 : ***** *****
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);
Currently in my code I have something in a for loop similar to:
bstr = bstr + x.charAt(i) + x.charAt(i>>4) + x.charAt(i>>8);
Where i is an integer and the loop variable and x is a static final constant string of characters. bstr could be in the order of KBs.
Thanks
A performant way to do this is to use a StringBuilder to concatenate your string:
StringBuilder builder = new StringBuilder();
for(int i = 0; i < count; i++){
builder.append(x.charAt(i));
builder.append(x.charAt(i>>4));
builder.append(x.charAt(i>>8));
}
return builder.toString();
This technique avoids the problem of storing all the copies of Strings between concatentations across the for loop.
edit:
or does this work for you (without adding chars one at a time):
StringBuilder builder = new StringBuilder();
for(int i = 0; i < count; i++){
builder.append(x);
}
return builder.toString();
Create a StringBuilder before the loop and reuse it:
StringBuilder sb = new StringBuilder();
while (someCondition) {
...
sb.append(x.charAt(i))
.append(x.charAt(i >> 4))
.append(x.charAt(i >> 8));
...
}
bstr = sb.toString();
Use a StringBuilder and just append while you're looping.
StringBuilder sb = new StringBuilder();
sb.append(bstr);
for(int i=0; i < somecondition; i++){
sb.append(x.charAt(i)).append(x.charAt(i>>4)).append(x.charAt(i>>8));
}
System.out.println(sb.toString());
One option is to use the StringBuilder class. It has an internal array of char, which it appends your contents to until you call the toString method, at which point it creates a new String object. Of course, since it's using an array to store your characters, it may run out of space, at which point it will copy the contents into a new larger array. You can avoid that by initially giving it a capacity that will be large enough to hold the final String.
// Create a new StringBuilder with an initial capacity that is a little larger than the final String
StringBuilder builder = new StringBuilder(estimatedSizeOfFinalString);
int i = 0;
while (loopConditionIsTrue) {
builder.append(x.charAt(i)).append(x.charAt(i >> 4)).append(x.charAt(i >> 8);
}
String bstr = builder.toString();
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 : ***** *****