String concatenation not working, or is it a bug - java

I have written some code and used a string that I concatentated using the += (as I only do it a couple of times.
Later on I used another string and used the concat() function. and the concatenation didn't work.
So I wrote a little method in Junit (with eclipse)...
#Test
public void StingConcatTest(){
String str = "";
str += "hello ";
str += " and goodbye";
String conc="";
conc.concat("hello ");
conc.concat(" and goodbye");
System.out.println("str is: " + str + "\nconc is: "+ conc);
The output is...
str is: hello and goodbye
conc is:
So either I'm going mad, I'm doing something wrong (most likely), there is an issue in JUNIT, or there is a problem with my JRE / eclipse or something.
Note that stringbuilders are working fine.
David.

Ok, we see this question at least couple of times a day.
Strings are immutable, so all operations on String results in new String.
conc= conc.concat("hello "); you need to reassign result to string again

You have to try with:
String conc="";
conc = conc.concat("hello ");
conc = conc.concat(" and goodbye");
System.out.println("str is: " + str + "\nconc is: "+ conc);
For sake of optimization you can write:
String conc="";
conc = conc.concat("hello ").concat(" and goodbye");
System.out.println("str is: " + str + "\nconc is: "+ conc);

If you plan on concatenating multiple Strings you could also use StringBuilder:
StringBuilder builder = new StringBuilder();
builder.append("hello");
builder.append(" blabla");
builder.append(" and goodbye");
System.out.println(builder.toString());

concat returns a String. It doesn't update the original String.

concat() returns the concatenated string.
public static void main(String [] args) {
String s = "foo";
String x = s.concat("bar");
System.out.println(x);
}

String.concat doesn't change the string it is called on - it returns a new string which is the string and the argument concatenated together.
By the way: string concatenation using concat or += is not very performant. You should use the class StringBuilder instead.

Related

java find and replace %

In java 1.8.0
I am trying to replace %, but it is not matching
String str = "%28Sample text%29";
str.replaceAll("%29", "\\)");
str.replaceAll("%28", "\\(");
System.out.println("Replaced string is " + str);
I have tried all this Replace symbol "%" with word "Percent" Nothing worked for me. Thanks in Advance.
It's working.
You need re-assign to str
str = str.replaceAll("%29", "\\)");
str = str.replaceAll("%28", "\\(");
Jerry06's answer is correct.
But you could do this simply by using URLDecoder to decode those unicode value.
String s = "%28Hello World!%29";
s = URLDecoder.decode(s, "UTF-8");
System.out.println(s);
Will output :
(Hello World!)
The problem is that you misunderstood the usage of replaceall. It's for regex based replacements. What you need to use is the normal replace method like that:
String str = "%28Sample text%29";
str=str.replace("%29", "\\)"). replace("%28", "\\(");
System.out.println("Replaced string is " + str);

Is there any simpler code to separate lines?

I am using this code to separate the next line and giving space.
String sms="Name:"+name+ System.getProperty ("line.separator")+System.getProperty
("line.separator")+"ContactNumber:"+contactnumber+ System.getProperty
("line.separator")+"Quantity:"+quantity+System.getProperty
("line.separator")+"Number.of.Pcs:"+noofpieces+System.getProperty
("line.separator")+"Date and Time:"+dateandtime
+System.getProperty ("line.separator")+"Delivary
Address:"+deliveryaddress;
You could use a StringBuilder instance and then use the new line operator appended to the StringBuilder. For example:
StringBuilder sb = new StringBuilder();
sb.append("Name: ").append(name);
sb.append("\n"); // for a new line.
Whatever the case, I would strongly recommend that you use a StringBuilder to append to a very large String.
In addition, you could also use System.lineSeparator(); However, that may only work in Java with the JVM with Java 7 and not in Android (so I would definitely check that out.)
String sms= "Name:" + name
+ "\nContactNumber:" + contactnumber
+ "\nQuantity:" + quantity
+ "\nNumber.of.Pcs:" + noofpieces
+ "\nDate and Time:" + dateandtime
+ "\nDelivary Address:" + deliveryaddress;
Using System.getProperty("line.separator") is a good practice as it will give you code that could be reused on another platform. To simplify your code, you can use TextUtils.join :
String sms = TextUtils.join(System.getProperty("line.separator"),
new String[] {
"Name:" + name ,
"ContactNumber:" + contactnumber,
...});
You could also use this solution
String format = "Name: %s%n%nContactNumber: %s%nQuantity: %s%nNumber.of.Pcs: %s%nDate and Time: %s%nDelivery Address: %s";
String sms = String.format(format, name, contactnumber, quantity, noofpieces, dateandtime, deliveryaddress);
The explanation of the format placeholders you find in the Javadoc for java.util.Formater

Android - Editing my String so each word starts with a capital

I was wondering if someone could provide me some code or point me towards a tutrial which explain how I can convert my string so that each word begins with a capital.
I would also like to convert a different string in italics.
Basically, what my app is doing is getting data from several EditText boxes and then on a button click is being pushed onto the next page via intent and being concatenated into 1 paragraph. Therefore, I assume I need to edit my string on the intial page and make sure it is passed through in the same format.
Thanks in advance
You can use Apache StringUtils. The capitalize method will do the work.
For eg:
WordUtils.capitalize("i am FINE") = "I Am FINE"
or
WordUtils.capitalizeFully("i am FINE") = "I Am Fine"
Here is a simple function
public static String capEachWord(String source){
String result = "";
String[] splitString = source.split(" ");
for(String target : splitString){
result
+= Character.toUpperCase(target.charAt(0))
+ target.substring(1) + " ";
}
return result.trim();
}
The easiest way to do this is using simple Java built-in functions.
Try something like the following (method names may not be exactly right, doing it off the top of my head):
String label = Capitalize("this is my test string");
public String Capitalize(String testString)
{
String[] brokenString = testString.split(" ");
String newString = "";
for(String s : brokenString)
{
s.charAt(0) = s.charAt(0).toUpper();
newString += s + " ";
}
return newString;
}
Give this a try, let me know if it works for you.
Just add android:inputType="textCapWords" to your EditText in layout xml. This wll make all the words start with the Caps letter.
Strings are immutable in Java, and String.charAt returns a value, not a reference that you can set (like in C++). Pheonixblade9's will not compile. This does what Pheonixblade9 suggests, except it compiles.
public String capitalize(String testString) {
String[] brokenString = testString.split(" ");
String newString = "";
for (String s : brokenString) {
char[] chars = s.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
newString = newString + new String(chars) + " ";
}
//the trim removes trailing whitespace
return newString.trim();
}
String source = "hello good old world";
StringBuilder res = new StringBuilder();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
System.out.print("Result: " + res.toString().trim());

removing space before new line in java

i have a space before a new line in a string and cant remove it (in java).
I have tried the following but nothing works:
strToFix = strToFix.trim();
strToFix = strToFix.replace(" \n", "");
strToFix = strToFix.replaceAll("\\s\\n", "");
myString.replaceAll("[ \t]+(\r\n?|\n)", "$1");
replaceAll takes a regular expression as an argument. The [ \t] matches one or more spaces or tabs. The (\r\n?|\n) matches a newline and puts the result in $1.
try this:
strToFix = strToFix.replaceAll(" \\n", "\n");
'\' is a special character in regex, you need to escape it use '\'.
I believe with this one you should try this instead:
strToFix = strToFix.replace(" \\n", "\n");
Edit:
I forgot the escape in my original answer. James.Xu in his answer reminded me.
Are you sure?
String s1 = "hi ";
System.out.println("|" + s1.trim() + "|");
String s2 = "hi \n";
System.out.println("|" + s2.trim() + "|");
prints
|hi|
|hi|
are you sure it is a space what you're trying to remove? You should print string bytes and see if the first byte's value is actually a 32 (decimal) or 20 (hexadecimal).
trim() seems to do what your asking on my system. Here's the code I used, maybe you want to try it on your system:
public class so5488527 {
public static void main(String [] args)
{
String testString1 = "abc \n";
String testString2 = "def \n";
String testString3 = "ghi \n";
String testString4 = "jkl \n";
testString3 = testString3.trim();
System.out.println(testString1);
System.out.println(testString2.trim());
System.out.println(testString3);
System.out.println(testString4.trim());
}
}

How to remove " " from java string

I have a java string with " " from a text file the program accesses with a Buffered Reader object. I have tried string.replaceAll(" ","") and it doesn't seem to work.
Any ideas?
cleaned = cleaned.replace(" "," ");
cleaned = cleaned.replace("\u00a0","")
This is a two step process:
strLineApp = strLineApp.replaceAll("&"+"nbsp;", " ");
strLineApp = strLineApp.replaceAll(String.valueOf((char) 160), " ");
This worked for me. Hope it helps you too!
The same way you mentioned:
String cleaned = s.replace(" "," ");
It works for me.
There's a ready solution to unescape HTML from Apache commons:
StringEscapeUtils.unescapeHtml("")
You can also escape HTML if you want:
StringEscapeUtils.escapeHtml("")
Strings are immutable so You need to do
string = string.replaceAll(" ","")
You can use JSoup library:
String date = doc.body().getElementsByClass("Datum").html().toString().replaceAll(" ","").trim();
String.replace(char, char) takes char inputs (or CharSequence inputs)
String.replaceAll(String, String) takes String inputs and matches by regular expression.
For example:
String origStr = "bat";
String newStr = str.replace('a', 'i');
// Now:
// origStr = "bat"
// newStr = "bit"
The key point is that the return value contains the new edited String. The original String variable that invokes replace()/replaceAll() doesn't have its contents changed.
For example:
String origStr = "how are you?";
String newStr = origStr.replaceAll(" "," ");
String anotherStr = origStr.replaceAll(" ","");
// origStr = "how are you?"
// newStr = "how are you?"
// anotherStr = howareyou?"
We can have a regular expression check and replace HTML nbsp;
input.replaceAll("[\\s\\u00A0]+$", "") + "");
It removes non breaking spaces in the input string.
My solution is the following, and only this worked for me:
String string = stringWithNbsp.replaceAll("NNBSP", "");
Strings in Java are immutable. You have to do:
String newStr = cleaned.replaceAll(" ", "");
I encountered the same problem: The inner HTML of the element I needed had "&nbsp" and my assertion failed.
Since the question has not accepted any answer,yet I would suggest the following, which worked for me
String string = stringwithNbsp.replaceAll("\n", "");
P.S : Happy testing :)

Categories