【问题标题】:java replace all on multi line stringjava全部替换多行字符串
【发布时间】:2015-03-06 03:01:02
【问题描述】:

试图用java中另一个字符串的内容替换一个字符串中的标签。

searchString 是我从文本文件中读取的标题。 replaceString 是另一个变长字符串(bodyString)的长度

代码是:

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("****************************************");

它输出:

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

我怀疑我遇到了多行问题,但似乎无法克服它。

任何建议表示赞赏...

【问题讨论】:

标签: java replaceall


【解决方案1】:

你想要

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

在 Java 中,Strings 是不可变的。如果你想要一个新的字符串,你需要通过构造函数调用或许多工厂方法之一来获取一个新的字符串。

【讨论】:

    猜你喜欢
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    相关资源
    最近更新 更多