Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
A program that takes the first two characters of a string and adds them to the front and back of the string. Which version is better?
public String front22(String str) {
if(str.length()>2) return str.substring(0,2)+str+str.substring(0,2);
return str+str+str;
}
or
public String front22(String str) {
// First figure the number of chars to take
int take = 2;
if (take > str.length()) {
take = str.length();
}
String front = str.substring(0, take);
return front + str + front;
}
The former strikes me as more elegant. The latter is easier to understand. Any other suggestions for improvement of either is more than welcome!
Issue with the first option, mainly because string is immutable. [Edit.] As #Pshemo correctly pointed out, my statement was unclear. Quoting #Pshemo, "executing same substring twice is inefficient when we can reuse result from first substring".
Use a StringBuilder.
StringBuilder sb = new StringBuilder(str);
CharSequence seq = sb.subSequence(0,2);
sb.insert(0, seq);
sb.append(seq);
return sb.toString();
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to split a String at every Nth occurence, but missing the last values.Here is what is expected.
Input : String str = "234-236-456-567-678-675-453-564";
Output :
234-236-456
567-678-675
453-564
Here N=3, where the str should be split at every 3rd occurence of -.
Try this.
String str = "234-236-456-567-678-675-453-564";
String[] f = str.split("(?<=\\G.*-.*-.*)-");
System.out.println(Arrays.toString(f));
result:
[234-236-456, 567-678-675, 453-564]
You can try the following with Java 8:
String str = "234-236-456-567-678-675-453-564";
Lists.partition(Lists.newArrayList(str.split("-")), 3)
.stream().map(strings -> strings.stream().collect(Collectors.joining("-")))
.forEach(System.out::println);
Output:
234-236-456
567-678-675
453-564
Maybe one of the worst way without using function available in java , but good like exercise :
public static void main(String[] args){
String s = "234-236-456-567-678-675-453-564";
int nth =0;
int cont =0;
int i=0;
for(;i<s.length();i++){
if(s.charAt(i)=='-')
nth++;
if(nth == 3 || i==s.length()-1){
if(i==s.length()-1) //with this if you preveent to cut the last number
System.out.println(s.substring(cont,i+1));
else
System.out.println(s.substring(cont,i));
nth=0;
cont =i+1;
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a url which is generate on the fly and i want to place some text with unknowing text using string builder. Please let me know how?
Example:-
http://localhost/abcdef/servlet/cpd.abcd.build.coupons.CouponValueFormatterServlet?dsn=frd_abcdef&lang=ENG&val=PRCTXT|ABCDE_-1223344&classGroupid=101,201&fgcolor=000000&bgcolor=E0DBD8&width=100&height=80&fontSize=11&fontWeight=normal.
The above URL is a string builder and "val=PRCTXT|ABCDE_-1223344" text has to change with "val=123456" text. But here Val is always user input . so it is changing always.
If you absolute want to use StringBuilder, you should read the javadoc to find usable methods for your purpose.
That would be:
indexOf(String str)
indexOf(String str, int fromIndex)
replace(int start, int end, String str)
StringBuilder buf = new StringBuilder("http://localhost/abcdef/servlet/cpd.abcd.build.coupons.CouponValueFormatterServlet?dsn=frd_abcdef&lang=ENG&val=PRCTXT|ABCDE_-1223344&classGroupid=101,201&fgcolor=000000&bgcolor=E0DBD8&width=100&height=80&fontSize=11&fontWeight=normal.");
int start = buf.indexOf("&val=");
if (start != -1) {
start += 5;
int end = buf.indexOf("&", start);
if (end == -1)
end = buf.length();
buf.replace(start, end, "123456");
System.out.println(buf);
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Ex String Param=Value1:100,Value2:2000,Value3:30000:
What is the best way in java to trim the above mentioned string format to get the First element's value?
Result should be 100 (from the above mentioned Ex string param).
Assuming you have a String e = "Value1:100,Value2:2000,Value3:30000";
Your next step would be to analyze its structure. In this case it is very simple key:value which is comma separated.
We have to split at every "," and then ":".
String[] keyValues = e.split(",");
for(String keyValue : keyValues) {
String tupel = keyValue.split(":");
// tupel[0] is your key and tupel [1] is your value
}
You can now work with this. You can add these to a map to access it by name.
Also this How to search a string of key/value pairs in Java could be worth looking at.
If you only want the first value, you can take a substring up to the first ',':
String p = "Value1:100,Value2:2000,Value3:30000:";
int firstComma = p.indexOf(',');
if(firstComma >= 0) {
p = p.substring(0, firstComma);
}
String tuple[] = p.split(":");
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Two methods of implementing a string. A counted string explicitly
records its length. The terminated string’s length is determined by an
end-of-string mark.
Can anyone give an example of counted string and a terminated string in java.
CountedString {
char[] string;
int length;
int getLength() {
return length;
}
}
TerminatedString {
char[] string;
final static char TERMINATOR = '$';
int getLength() {
for (int i = 0; i < string.length; i++) {
if (string[i] == TERMINATOR) return i;
}
}
}
If you look in to the String.java will find that the length of String is being calculated by counter which traverse through string's characters .
Please referString.java for more information. You should look in to this class to see implementation of length() method.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
List<String> test
which contains several items,
what would be the quickest way to output a string as "item1 item2 item3"?
If you've got Guava included in your project,
System.out.println(Joiner.on(' ').join(myList));
I assume you mean "quickest in terms of debugging".
If it's a List<String> itemList
for (String item : itemList) {
System.out.print(item + " ");
}
System.out.println();
Helper function that leverages string builder for efficiency and allows passing any delimiter.
public String join(List list, String delim)
{
StringBuilder sb = new StringBuilder();
for (String str : list)
{
sb.append(str + delim);
}
sb.delete(sb.length() - delim.length(), sb.length());
return sb.toString();
}
System.out.print(stringsList);
You just need to do this, comma and space seperated strings will be printed on console, quickest is ambiguous term though.