I think I'm missing something here -- string.replace() - java

I have the code
String txt = "<p style=\"margin-top: 0\">";
txt.replace("style=\"margin-top: 0\"","class=\"style_" + i + "\"");
In a for loop (which is what the i is for), but when I run this, nothing gets replaced. Am I using this wrong?

It should look like this:
String txt = "<p style=\"margin-top: 0\">";
txt = txt.replace("style=\"margin-top: 0\"","class=\"style_" + i + "\"");
"String" is an immutable type, which means that methods on a String do not change the String itself. More info here - http://en.wikipedia.org/wiki/Immutable_object.

The replace method does not modify the string on which it is called but instead returns the reference to the modified string.
If you want txt to refer to the modified string you can do:
txt = txt.replace("style=\"margin-top: 0\"","class=\"style_" + i + "\"");
If you want txt to continue to refer to the original string and want a different reference to refer to the changed string you can do:
String new_txt = txt.replace("style=\"margin-top: 0\"","class=\"style_" + i + "\"");

String is a immutable class, which means instance methods of a String object don't alter the string itself. You have to gather the return value of those instance methods.

Related

Parse a plain text into a Java Object

I´m parsing a plain text and trying to convert into an Object.
The text looks like(and i can´t change the format):
"N001";"2014-08-12-07.11.37.352000";" ";"some#email.com ";4847 ;"street";"NAME SURNAME ";26 ;"CALIFORNIA ";21
and The Object to convert:
String index;
String timestamp;
String mail;
Integer zipCode
...
I´ve tried with:
StringTokenizer st1 = new StringTokenizer(N001\";\"2014-08-12-07.11.37.352000\";\" \";\"some#email.com \";4847 ;\"street\";\"NAME SURNAME \";26 ;\"CALIFORNIA \";21);
while(st2.hasMoreTokens()) {
System.out.println(st2.nextToken(";").replaceAll("\"",""));
}
And the output is the correct one, i´ve thinking to have a counter and hardcoding with a case bucle and set the field deppending the counter, but the problem is that I have 40 fields...
Some idea?
Thanks a lot!
String line = "N001";"2014-08-12-07.11.37.352000";" ";"some#email.com ";4847 ;"street";"NAME SURNAME ";26 ;"CALIFORNIA ";21
StringTokenizer st1 = new StringTokenizer(line, ";");
while(st2.hasMoreTokens()) {
System.out.println(st2.nextToken().replaceAll("\"",""));
}
Or you can use split method and directly get a array of values using the delimiter ;
String []values = line.split(";");
then iterate through the array and get and cast the values they way you want
Regardless of the way you are parsing the file, you somehow need to define the mapping of column-to-field (and how to parse the text).
if this is a CVS file, you could use a library like super-csv. All you need to do is write a mapping definition.
I would first split your input String based on the semi-colon separator, then clean up the values.
For instance:
String input = "\"N001\";\"2014-08-12-07.11.37.352000\";\" " +
"\";\"some#email.com " +
"\";4847 ;\"street\";\"NAME " +
"SURNAME \";26 ;\"CALIFORNIA " +
"\";21 ";
// raw split
String[] split = input.split(";");
System.out.printf("Raw: %n%s%n", Arrays.toString(split));
// cleaning up whitespace and double quotes
ArrayList<String> cleanValues = new ArrayList<String>();
for (String s: split) {
String clean = s.replaceAll("[\\s\"]", "");
if (!clean.isEmpty()) {
cleanValues.add(clean);
}
}
System.out.printf("Clean: %n%s%n", cleanValues);
Output
Raw:
["N001", "2014-08-12-07.11.37.352000", " ", "some#email.com ", 4847 , "street", "NAME SURNAME ", 26 , "CALIFORNIA ", 21 ]
Clean:
[N001, 2014-08-12-07.11.37.352000, some#email.com, 4847, street, NAMESURNAME, 26, CALIFORNIA, 21]
Note
In order to map the values to your variables you will need to know their index in advance, and it will have to be consistent.
Then you can use the get(int i) method to retrieve them from your List - e.g. cleanValues.get(2) will get you the e-mail, etc.
Note (2)
If you do not know the indices in advance or they may vary, then you are in trouble.
You can of course try to get those indices by using regular expressions but I suspect you might end up complicating your life quite a bit.
you can use Java Reflection to automate your process.
Iterate over the fields
Field[] fields = dummyRow.getClass().getFields();
and set your values
SomeClass object = construct.newInstance();
field.set(object , value);

Using HTML code in Swing

I can't figure out how to use variables in HTML, string is a variable in this case.
JOptionPane.showMessageDialog(null,"<html>Error #1<br> + string +</html>","Error",JOptionPane.PLAIN_MESSAGE);
this output: Error #1 + string
JOptionPane.showMessageDialog(null,"<html>Error #1<br></html>" + string ,"Error",JOptionPane.PLAIN_MESSAGE);
this output: Error #1
is there a way to use string variables in HTML?
Do you want something like
"<html>Error #1<br>" + string + "</html>"
?
If you want to concatenate the string variable to the html you have there, it must be outside the quotes, otherwise it will be treated as a literal, as in your example.
JOptionPane.showMessageDialog(
null,
"<html>Error #1<br>" + string + "</html>",
"Error",
JOptionPane.PLAIN_MESSAGE);
Though note that logically JOptionPane.PLAIN_MESSAGE should be JOptionPane.ERROR_MESSAGE.
You need to do: "<html>Error #1<br>" + string + "</html>"
A string literal in java consists of zero or more characters enclosed in double quotes. So anything satisfies this condition will also be regarded as string too. You will need to close the String before appending the string.
So if the string = "Hi to stack":
Then "<html>Error #1<br>" + string + "</html>" will result in:
"<html>Error #1<br>Hi to stack</html>"

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

Concatenating url in jsp

I want to concatenate url with the value of string variable.
Example
string filename="example"
string extention="txt"
<a href="myuploads/(value of filename).(value of extention)">
How can I do that ?
String filename = "example"
String extension = "txt"
String url = "myuploads/" + filename + "." + extension
I the JSP :
<a href='<%= url%>'></a>
Instead of declaring another variable it can be done like this as well :
Usage of unnecessary variables must be curbed whenever and wherever applicable .

Insert java variable in html-styled jTextPane

I'm building a Java Swing interface in which I have a HTML-styled jTextPane, which I use for displaying the current system status. I want to be able to display a few Strings (which may change over time), while using HTML to set the appearance and placement of the text. I use the line of code below to display two strings of them in the jTextPane.
jTextPane1.setText("<html><font size=\"4\" ><b><center> String A here! </center></b></font><br><br><font size=\"3\" ><center> String B here</center></font>");
What I want, is to insert two Strings (A and B) so that I can change them over time. But unfortunately, I cannot find the syntax to insert a String anywhere. Is there a simple way to do this? Thanks in advance.
Define your HTML code as template and use the placeholders %s for stringA and stringB. Then use String.format() to insert your strings. At the end set this in your TextPane.
String template = "<html><font size=\"4\" ><b><center>%s</center></b></font><br><br><font size=\"3\" ><center>%s</center></font>"
String text = String.format(template, stringA, stringB);
jTextPane1.setText(text);
jTextPane1.getDocument().insertString(offset, stringToInsert, attributes);
You can use some constant strings like:
final String PRE_HTML = "<html><font size=\"4\" ><b><center> ";
final String MID_HTML = " </center></b></font><br><br><font size=\"3\" ><center> ";
final String POST_HTML = "</center></font></html>";
And you can set like:
String strA = "String A";
String strB = "String B";
jTextPane1.setText(PRE_HTML + strA + MID_HTML + strB + POST_HTML);
You could use String.format:
jTextPane1.setText(String.format("<html><font size=\"4\" ><b><center> %s </center></b></font><br><br><font size=\"3\" ><center> %s </center></font>", a, b));

Categories