刪除\ n之間的子想從一個字符串中刪除\n
之間的子字符串,如果它包含"FALSE"
關鍵詞..我如何從一個字符串在java中
mainString = "hi my name is john \n I am a architect \n hello FALSE \n have a nice day \n"
我想刪除"\n hello FALSE \n"
。我試圖string.replace
但沒有成功..
刪除\ n之間的子想從一個字符串中刪除\n
之間的子字符串,如果它包含"FALSE"
關鍵詞..我如何從一個字符串在java中
mainString = "hi my name is john \n I am a architect \n hello FALSE \n have a nice day \n"
我想刪除"\n hello FALSE \n"
。我試圖string.replace
但沒有成功..
您可以分割每個 「\ n」 如下
String[] lines = message.split("\n"); //considering that message variable holds the String
String msg="";
for(int cnt = 0;cnt<lines.length;cnt++)
{
if(!lines[cnt].contains("FALSE"))
{
msg+=lines[cnt]+"\n";
}
}
System.out.println(msg);
String content = "hi my name is john \n i am a architect \n hello FALSE \n have a nice day \n";
final StringBuilder sb = new StringBuilder();
final String newLine = "\n";
for (String line : content.split(newLine)) {
if(!line.contains("FALSE")){
sb.append(line).append(newLine);
}
}
System.out.println(sb.toString());
您可以使用正則表達式表達和replaceAll()
方法從String
之間的字符串:
string.replaceAll("\n.*FALSE.*\n", "");
告訴我們你試過的東西 –