Java 删除字符串开头和结尾的空白,不带trim()
如何在不使用Java 删除字符串开头和结尾的空白,不带trim(),java,string,Java,String,如何在不使用trim()方法的情况下删除字符串开头和结尾的空白 这是我的密码 public class StringTest { public static void main(String[] args) { String line = " Philippines| WNP|Naga |Camarines Sur|Naga Airport "; //System.out.println(line);
trim()
方法的情况下删除字符串开头和结尾的空白
这是我的密码
public class StringTest {
public static void main(String[] args) {
String line = " Philippines| WNP|Naga |Camarines Sur|Naga Airport ";
//System.out.println(line);
int endIndex = line.indexOf("|");
String Country = line.substring(0, endIndex);
line = line.substring(endIndex + 1);
int endIndexCountry = line.indexOf("|");
String Code = line.substring(0, endIndexCountry);
line = line.substring(endIndexCountry + 1);
int endIndexCode = line.indexOf("|");
String City = line.substring(0, endIndexCode);
line = line.substring(endIndexCode + 1);
int endIndexCity = line.indexOf("|");
String State = line.substring(0, endIndexCity);
line = line.substring(endIndexCity + 1);
System.out.print("Code:" + Code + "____");
System.out.print("Country:" + Country + "____");
System.out.print("State:" + State + "____");
System.out.print("City:" + City + "____");
System.out.println("Airport:" + line+ "____");
}
}
我的输出是这样的
Code: WNP____Country: Philippines____State:Camarines Sur____City:Naga ____Airport:Naga Airport ____
我需要看起来像这样(没有空格)
如何删除字符串开头和结尾的空白,而不使用
使用trim()方法
您可以使用正则表达式模式和String::replaceAll
的组合来实现
public class Main {
public static void main(String[] args) {
String str = " Hello ";
System.out.println("Before: " + str + "World!");
str = str.replaceAll("^[ \\t]+", "").replaceAll("[ \\t]+$", "");
System.out.println("After: " + str + "World!");
}
}
输出:
Before: Hello World!
After: HelloWorld!
1) 这与挥杆无关。2) …为什么不使用trim()
?我正在编辑我的代码@andrewhompson立即检查如果出于某种原因不想使用框中的trim方法,您需要实现自己的trim方法。你需要帮助吗?是的,我需要删除第一个空格和最后一个空格。我只能使用indexof()、Substring()和replace()methods@sandunwijerathneJerry-我希望这个解决方案对你有用。不要忘记接受答案,这样将来的访问者也可以自信地使用解决方案。检查以了解如何做。如有任何疑问/问题,请随时发表评论。
Before: Hello World!
After: HelloWorld!