0

trying to replace a tag in a string with the contents of another string in java.

The searchString is a header which I read from a text file. The replaceString is the length of another variable length string (bodyString)

The code is:

String replaceString = Integer.toString(bodyString.length());
System.out.println("****************************************");
System.out.println("Body String: " + bodyString);
System.out.println("\nBody Length: " + replaceString);  
System.out.println("\nSearch String: " + searchString);
if (searchString.contains("ContentLength")){
    System.out.println("\nfound ContentLength in string");
    searchString.replaceAll("ContentLength", replaceString);
}  
System.out.println("\nSearch String: " + searchString);
System.out.println("****************************************");

It outputs:

****************************************
Body String: 0425742196,1234,13:36:47,

Body Length: 26

Search String: HTTP/1.1 200 OK
Date: Mon, 02 Dec 2013 08:57:36 GMT
Server: IBM_HTTP_Server
Cache-Control: no-cache
Content-Length: ContentLength
Set-Cookie: JSESSIONID=0000hzYFq3Sa-rl7ywJMrGTF0he:186g6992j; Path=/
Set-Cookie: PLAY_ERRORS=""; Path=/locationsapi/
Expires: Thu, 01 Dec 1994 16:00:00 GMT
Connection: close
Content-Type: application/text; charset=utf-8
Content-Language: en-AU

found content in string

Search String: HTTP/1.1 200 OK
Date: Mon, 02 Dec 2013 08:57:36 GMT
Server: IBM_HTTP_Server
Cache-Control: no-cache
Content-Length: ContentLength
Set-Cookie: JSESSIONID=0000hzYFq3Sa-rl7ywJMrGTF0he:186g6992j; Path=/
Set-Cookie: PLAY_ERRORS=""; Path=/locationsapi/
Expires: Thu, 01 Dec 1994 16:00:00 GMT
Connection: close
Content-Type: application/text; charset=utf-8
Content-Language: en-AU
****************************************

I suspect I've got a problem with multiple lines but cant seem to overcome it.

Any advice appreciated...

  • Doesn't work because `String`s are immutable. I feel this must be a duplicate but I can't find a question that it's a duplicate of. – Vitruvie Jan 08 '15 at 04:03
  • possible duplicate of [String.replace() not replacing characters](http://stackoverflow.com/questions/12734721/string-replace-not-replacing-characters) – smac89 Jan 08 '15 at 04:04
  • possible duplicate of [Hints for java.lang.String.replace problem?](http://stackoverflow.com/questions/1166905/hints-for-java-lang-string-replace-problem) – shree.pat18 Jan 08 '15 at 04:05

1 Answers1

2

You want

searchString = searchString.replaceAll("ContentLength", replaceString)

In Java, Strings are immutable. If you want a new String, you need to get a new String, either by constructor call or by one of the many factory methods.

Christian Hujer
  • 17,035
  • 5
  • 40
  • 47