replace 1 « string « Java Data Type Q&A

1. Simplest way to use "BeanUtils alike" replace

Is there any libraries that would allow me to use the same known notation as we use in BeanUtils for extracting POJO parameters, but for easily replacing placeholders in a string? I ...

2. String replace function

I have following string

String str = "replace :) :) with some other string";
And I want to replace first occurance of :) with some other string And I used str.replaceFirst(":)","hi"); it gives following exception

3. Faster alternatives to replace method in a Java String?

The fact that the replace method returns a string object rather than replacing the contents of a given string is a little obtuse (but understandable when you know that strings are ...

4. Hints for java.lang.String.replace problem?

I would like to replace "." by "," in a String/double that I want to write to a file. Using the following Java code

double myDouble = myObject.getDoubleMethod(); // returns 38.1882352941176

String myDoubleString = ...

5. Replace last string

I want to replace the last String which is a "," with ")" Suppose the string is

Insert into dual (name,date,
to be converted to
Insert into dual(name,date)

6. How to replace all non-letters in a given string s by symbol '*'

For example Input

Hello 1/(ยค
Output should be
Hello ****

7. unble to replace string

This is my replace method in java but unble to replace for following. It replace only one \ Please help. If any body have any different method for replace? I had tried java ...

8. String replacement problem

I want to provide some template for a code generator I am developing. A typical pattern for class is :

public ${class_type} ${class_name} extends ${super_class} implements ${interfaces} {


Problem is if super_class is ...

9. Reformatting a Java String

I have a string that looks like this:

and I need to edit it to look like
Caldari Starship Engineering
Unfortunately it's three in the morning and I cannot for the life of me ...

10. Replace $ sign in String

I used the following line to remove all $ signs and spaces in a given data "DATA":

String temp_data = DATA.replaceAll("$", "").replaceAll(" ", "");
But it won't remove the $ signs, only the ...

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

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 ...

12. Java String: Replace string

How could I replace the "String" $1 in Java? I tried this but this don't replace it:

System.out.println(someHTMLCodeAsString.replaceAll("$1", "REPLACED"));

13. Java replace all non-HTML Tags in a String

I'd like to replace all the tag-looking parts in a String if those are not valid HTML tags. A tag-looking part is something enclosed in <> brackets. Eg. <> or <hello> but ...

14. Replacing the default String class with a custom class in Java

I would like to implement my own String class and get Java to use it when I am using double quotes.
It should look like that: MyString s = "foo" and the ...

15. replace String with another in java

What function can replace a string with another string? Example #1: What will replace "HelloBrother" with "Brother"? Example #2: What will replace "JAVAISBEST" with "BEST"? Thank you!

16. java:replacing " with \"

How can I escape the double quotes in a string? For eg,

input: "Nobody"
output:  \"Nobody\"
I tried sth like this,which is not working:
String name = "Nobody";
name.replaceAll("\"", "\\\"");

17. Fastest way to replace data in Java

I need to write a Java method that will:

  • retrieve HTML from a data table
  • search the HTML for a specific marker (embedded within a comment)
  • replace that marker with more HTML
For example, The ...

18. Unable to replace certain string items in java

I want this function to replace the '@'s and '#'s with the words from the string array and output a list.

import java.util.ArrayList;
import java.util.List;

public class Test {


19. How to replace comma (,) with a dot (.) using java

I am having a String str = 12,12 I want to replace the ,(comma) with .(Dot) for decimal number calculation, Currently i am trying this :

 if( str.indexOf(",") != -1 )

20. Handling multiple string replacements

I'm using Java. I have to replace a lot of strings using readLines[i].replace("string1", "string2") command. 190 strings, if you must know. However, some replace methods are not working. I write:

for (i=0; ...

21. how do i replace any string with a "$ " in java?

Using replaceAll() is giving me a rexex exception. This is the code I am using:

public class test {

    public static void main(String[] args) {

22. Java String replace not working

String delimiter = "\\*\\*";
String html = "<html><head></head><body>**USERNAME** AND **PASSWORD**</body></html>";
Map<String, String> mp = new HashMap<String, String>();
mp.put("USERNAME", "User A");
mp.put("PASSWORD", "B");
for (Entry<String, String> entry : mp.entrySet()) {
  html.replace(delimiter + entry.getKey()+ delimiter, entry.getValue());
That should ...

23. java string replace best way to do

I have a String:

a0 + a1*ln(Hr) + a2*ln(St) + a3*ln(Tr)
This need to be converted in to:
a1 + a2*log(Hr[i]) + a3*log(St[i]) + a4*log(Tr[i])

24. renaming and replacing the contents of a string in java

String fileOne = "C:/1236.pdf"; String fileTwo = "C:/22.pdf"; String mergedFileLocation = "C:/myMergedData.pdf";
after the merging is done rename an existing file i need to ...

25. String Replace problem

What I have: I've got a text "Hi {0}, my name is {1}." I've got a List<String> names = Arrays.asList("Peter", "Josh"); I'm trying to fit Peter where there's a {0} and Josh where there's ...

26. How to Replace dot (.) in a string in java with /*/

i have a string i want to replace the DOT(.) with /*/ i.e my output will be persons/*/name i tried this code:

String a="\\*\\";
str=xpath.replaceAll("\\.", a);
but i am getting StringIndexOutOfBoundsException exceptions. Plese provide me ...

27. How to replace " \ " with " \\ " in java

I tried to break the string into arrays and replace \ with \ , but couldn't do it, also I tried String.replaceall something like this ("\","\"); . I want to supply ...

28. Replacing a part of a string with another

I am making a program that solves an equation. I have a variable that changes: i, and a string that is entered: parseLine What is the easiest way to make:

parseLine = "100 ...

29. Java on-the-fly string replacement

I've seen something like this in code

somestring = "Today is {0}, tomorrow is {1}";
I know that it'll put values into the string from another variable, but how do I do it? Update: ...

30. Do I need to do something special to use the replace method with symbols?

Here's some code

private String replaceToEncrypt(String password) {

31. How to replace || (two pipes) from a string with | (one) pipe

I am getting response for some images in json format within this tag:

"xmlImageIds":"57948916||57948917||57948918||57948919||57948920||57948921||57948? ?922||57948923||57948924||57948925||57948926||5794892"
What i want to do is to separate each image id using .split("||") of the string ...

32. String.replace

33. replacing string

I need help desparately. I have a XML file like this. I have tons of user in a database and I have to run this xml api for all the user. essentially I have to change the ...

35. String replace

Hi, Looks simple but need answer. May be it needs some trick which is not getting to this dumb mind. I have string[] st =new String[2]; st[0]= "Derek Leahy"; st[1]= "Joseph "Tony" Leahy"; st[0].replace(' ','+') gives me Derek+Leahy where as st[1].replace(' ','+') give only Joseph+ I need this answer to be Joseph+"Tony"+Leahy; Can some one help me to treak this trick. ...

36. Complex String Replacement

Hello; I have class=something and I need class="something". I was hoping to use tidy to clean this kind of thing up, but for various reason I can't. So.... fo_source = Pattern.compile("\\s?[a-z]+\\s?=\\s?[a-z]+\\s?").matcher(fo_source).replaceAll("\\s?[a-z]+\\s?=\"\\s?[a-z]+\\s?\""); NOTE: The expression is design to put quotes around any attribute set without them. This doesn't work. It finds all the incorrect attributes but replaces them with the expression I ...

37. multiple strings replacement

I need replace multiple (sub)Strings/ place holders in a (large)String with values in a single call. How to go about it? What is the best way? Is there anything available in java? I can use jdk1.4.2 only. eg. String origStr = " 0={0} 1={1} 2={2} "; String replacementVals[] = {"zero", "one", "two"}; String newStr = replace(origStr, replacementVals); After running the code, ...

38. string replacement ..

The arguments to replaceAll() are regular expressions. "[" introduces a character class. "[]" would be a meaningless empty character class, so it has a special meaning: a close bracket appearing right after an open bracket means that the character class contains a "]" character. You still have to provide the closing brace, though: "[]]". So this is why Java's giving you ...

39. having issues replacing strings

40. problem with String.replace

replaceAll does not perform a string replace, it performs a regular expression replace. And the pipe symbol is a special character in regular expressions, which does not mean its literal self. The javadocs for java.util.regex.Pattern have some of the gory details on that. You need to escape the symbol by a preceding backslash; then it is taken literally: replaceAll("\|","pipe") [ August ...

41. String Replacement

42. To replace square brackets from a string

Hi, Please let me know how to replace [ and ] from a string. code : public class Test{ public static void main(String[] args) { String s = "a\n\"a\"\ta\n [q]\\q$\tq"; System.out.println(s); s = s.replaceAll("[\\n\\t\\\\\"$/]*"," "); System.out.println(s); } } In this code i want to replace [ and ] from string s with space. What should i add to the regular expression ...

43. using string replace

44. String replacement

45. RegularExpression for string replacement

I have tried like this,but not able to achieve the desired output i am not able to create a correct reg exp String check ="&test;hf&test";//output should be &test;hf&test;test Pattern p = Pattern.compile("&test;"); // Create a matcher with an input string Matcher m = p.matcher(check); StringBuffer sb = new StringBuffer(); boolean result = m.find(); // Loop through and create a new String ...

47. Replace Acute Accent in a String

48. String replace function

public static String replace(String s, String repl, String with) { if (repl == null) return s; if (with == null) with = ""; int offset = 0; int p = s.indexOf(repl); while (p >= 0) { s = s.substring(0,p) + with + s.substring(p + repl.length()); offset = p + with.length(); p = s.indexOf(repl,offset); } return s; }

49. String replace???(Urgent)

50. String replace

51. Replacing String with BackSlash

52. String replace method problem

53. String replace

First you must understand how Strings are immutable. Then you describe exactly what you want. But a simplistic answer would be. String string1 = "String 1"; String string2 = "String 2"; string1 = string2; But be warned you must grasp the immutable quality of Strings, because this may not be doing what you expect it to do.

54. replacing %20 in a string

Why do you have an if statement? replaceAll() won't replace anything that isn't there. Of course, you may be worried about the cost of calling replaceAll() when there is nothing to replace. Does this happen very often? The current paradigm is to not worry about such optimizations until after you run code metrics to determine if it will make a significant ...

55. replacing string parts

If you're using JDK 5, you can also use path = path.replace("/", "\\"); The difference between replace() and replaceAll() is not obvious from the name - actually replace() replaces all occurrances of whatever you're replacing, much like replaceAll(). The real difference is that replace() is simple and does exacly what you'd expect it to do, while replaceAll() has more complex behavior. ...

56. String replace() method

Another remark with regard to your original idea: Replacing a character by a null character does not remove the original character from the string. It just replaces the character with another character with code 0. And I'll repeat what Fred and Alan said, because it's a very important notion: String is immutable, which means that you cannot modify a String after ...

57. Replace all "." in a string

58. how to replace colon (:) in a String

Hi You wrote: ------------------------------------------------------------- Hi Team, I have a requirement like replace the colon ( in a string. I tried with the following code: /** String str = "abc ef:ghi"; str.replaceAll(":","_"); system.out.println(str); **/ But the output i am getting the string with unchanged. output ---------- abc ef:ghi Could you please let me know why i am not able to replace the ...

59. Replace String

60. String replacement

Strings are immutable - mostly for safety/security reasons that are beyond me. Once made their contents are not altered. The replace() method is returning the altered string, but it needs a new home. String s = "test"; String x = s.replace("s", "x"); System.out.println(s); System.out.println(x); This turns test to text, but you won't see the result in s, only in x.

62. replace String input with parenthesis

63. How to get or replace the backslash in Java string

Hi, Henry, thanks for quick reply. I am doing some codes to validate a string not to include backslash "\". For example, user input "12345\6" and I have to check if it contains backslash. I try the followings but they does not work: loop check: for (int i=0; i

65. String Replace Problem

Hi, I'm rather new to Java. I would like to know why the following code doesn't work. I'm trying to parse the String named "string". My delimiters are topic, location, presenter and end. I try to loop through the string to grab all three instances (you'll notice there are three topics). However, after the second loop, it resets itself and gives ...


67. replacing string in java

String str8 = "Hello, John How are you? {{file:350}} with my name"; My requirement is that I want to replace {{file:350}} with some string. number 350 can change. How will i do this? Is their any approach? I was trying to do in this way but it give me exceptions as java.util.regex.PatternSyntaxException: Illegal repetition... String stro = str8.replaceAll("{*.?}", "00000"); System.out.println("Stro:"+stro); Does ...

68. replacing \' with ' in string

69. String Replace

70. String replacement

71. Replace " with ' in string

Campbell Ritchie wrote:And if you want a backslash you may have to escape it with a backslash. If " won't work try \" and if \" won't work try \\" and if \\" won't work try \\\" There is no need for trial and error. You just need to remember two things. First, the Java string literal does its parts first ...

72. String Replacement problem

73. String.replace - a different problem

I have a parent String - say "ABCHASOIOBBASJSKAKSLK" (something like that) I get input from the user as what replacement must be made for what substring of the parent String. The user might say 'replace BALL for B' and 'replace APPLE for A' and 'replace IOP for CHA'..... in the parent. The problem happens when I do serial replacements.That is, when ...

74. Replace Carriage Returns in String

I haven't done a lot of this type of string operations in Java. I've done a bunch of regex in JavaScript. What I'm not sure about is: 1. why you getString and such when replaceAll() is a String method ... i.e. why not rs.replaceAll() ? Does getString from a string make a copy that you're not saving anywhere (for example)? 2. ...

75. Replace property in String

Hi , public class test { public static void main(String[] args) { String a = "test"; System.out.println("the value of a before replace "+a); a.replace('t', 'q'); System.out.println("the value of a after replace "+a); } } In the above code , i m getting the output as the value of a before replace test the value of a after replace test I dont ...

76. String Replace and Replace All methods

77. simple string replace question

78. Replacing string

79. String replace

I have a web application running on Jetty that takes a SQL query as a string and replaces a specific character sequence with input from a web page. Using the replace command, it generates the SQL then runs the query. It works great and we have been using it for a while. Today I noticed that one query wasn't working. In ...

80. String replace

Thanks I tried it. Using Regular expression is working fine. I found one more scenario where my input string is like -12546-78956-85462 having length of 18 but my out put should be 000000000000000 should be 15. The -negative sign should not be replaced with ZERO. I tried using replaceAll as below but it did not work testdata=testdata.replaceAll("[0-9[^-]]", "0"); //still i get ...

81. how to replace ? with \? from string

82. String replace

83. Replace in a string

Please post your code, then it's easier for other people to tell you exactly how to fix the problem. Working with \ in Java source code can be a bit tricky, especially when dealing with regular expressions, because you have to escape the \ on multiple levels. Sometimes you need to write \\ or even \\\\ for a backslash.

84. Replace String

String importPath = getServletContext().getRealPath(IMPORT_DIR); String completeFilePath = importPath+"/"+d.getFileName(); File tempFile = new File(completeFilePath); fi.write(tempFile); // Convert the file to a string String content = FileUtils.readFileToString(tempFile); //Remove FM Mess. int begin = content.indexOf("

85. String replacement...

Then you've to think about the way of replacing stuff. You may keep things in a map and use, if you can. Sine I don't know the exact thing I cannot say exactly which way to go. Looking at your last post, I feel that you want to format a string, not replace, even both are quite similar.

86. Replace String with "*"

Say I have the word 'Mississippi'. The program I'm writing basically does asks the user for a number, and if that number is greater than 4, the given word (Mississippi) becomes masked with '*', so in this case, '***********'. But, if the user enters 3, then the given word is only masked up to every fourth letter, so for example, in ...

87. Java String Replace

88. String.replace ?!

89. String.replace function

90. String replacement

91. Re: How to replace a string

This is from the API: replace public String replace(CharSequence target, CharSequence replacement)Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab". Parameters: target - ...

92. Not able to replace a String to String.

Right click on the project name (in the project view) and select properties, then select Java Compiler. It will be on that page somewhere. I'm sure someone in the area there knows how to use your IDE, why did you not just ask the person sitting next to you? If there is noone sitting next to you, then why did you ...

93. String replace

94. string replace

Hi all, I have a requirement where in I want to replace a part of the string with null. My req, is I have a string "\\k:\Group\docs" and I want to remove the " " part at the start. I am unable to do this with the string replace method . Thanks

95. replace string

String.matches() tests using a regular expression if the whole String matches, not just a part of it. If you just want to replace all '-' with '_' then you need data = data.replace("-","_"); Note, your line data.replace("-","_"); would actually do nothing since String objects are immutable and this line returns a new String with the required changes but which you just ...

96. Re: String replace tokens

97. Re: String replace tokens

98. Replace commas in Java String

99. String.replace() does not seem to work.

There are some operations that can be performed on the original String that do not require another String to be created for a result (e.g. matches(), charAt()). When an operation would change the contents of the String a new String has to be created to represent what the result of the operation on the original String should be.

100. java string replace