[英]Easiest way to remove trailing tab in a string in java
例如,如果您有一個制表符分隔值的列表:
foo1\tfoo2\tfoo3\tfoo4\t
由於自動將\\ t附加到每個+=
因此添加了最后一個\\ t 。
如何輕松地刪除最后一個\\ t ? 這樣的結果是:
foo1\tfoo2\tfoo3\tfoo4
根據Hover的要求,以下是我所擁有的一個小例子:
String foo = "";
for (int i = 1; i <= 100; i++) {
foo += "foo" + "\t";
if (i % 10 == 0) {
foo = foo.trim(); // wasn't working
foo += "\n";
}
}
System.out.println(foo);
輸出(用字符串選項卡替換的實際選項卡,在此處顯示):
foo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\t
foo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\t
foo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\t
foo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\t
foo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\t
foo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\t
foo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\t
foo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\t
foo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\t
foo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\tfoo\t
這是我問這個問題的主要原因,.trim()無法正常工作,因此,我堅決不將trim()用於尾隨制表符。
String s1 = "foo1\tfoo2\tfoo3\tfoo4\t".trim();
String expectedString = "foo1\tfoo2\tfoo3\tfoo4\t".trim();
如果您只想刪除結尾的標簽,則可以執行以下操作:
String s1 = "foo1\tfoo2\tfoo3\tfoo4\t";
while (s1.endsWith("\t")) {
s1 = s1.substring(0, s1.length()-1);
}
如果你的循環看起來像這樣
for(...){
values += foo + number + "\t"
}
您可以
trim()
n-1
次迭代,並手動應用最后一個沒有選項卡的部分 n
次迭代添加一個顯式測試,而不應用“ \\ t”( values += foo + (i==n-1)? numbers:numbers+"\\t"
) HovercraftFullOfEels是正確的String#trim
應該做您想要的...
String testing = "foo1\tfoo2\tfoo3\tfoo4\t";
System.out.println("\"" + testing.trim() + "\"");
if (testing.endsWith("\t")) {
testing = testing.substring(0, testing.lastIndexOf("\t"));
System.out.println("\"" + testing + "\"");
}
哪個輸出...
"foo1 foo2 foo3 foo4"
"foo1 foo2 foo3 foo4"
更新
如果失敗了……
StringBuilder sb = new StringBuilder(testing);
while (sb.lastIndexOf("\t") == sb.length()) {
sb.delete(sb.length() - 1, sb.length());
}
System.out.println("\"" + sb.toString() + "\"");
可能有幫助...
為了澄清我們的討論,如果運行此命令,您會看到什么?
public class Foo3 {
public static void main(String[] args) {
String foo = "";
for (int i = 1; i <= 100; i++) {
if (i % 10 == 1) {
foo += "\"";
}
foo += "foo" + "\t";
if (i % 10 == 0) {
foo = foo.trim(); // wasn't working
foo += "\"\n";
}
}
System.out.println(foo);
}
}
我自己得到:
"foo foo foo foo foo foo foo foo foo foo" "foo foo foo foo foo foo foo foo foo foo" "foo foo foo foo foo foo foo foo foo foo" "foo foo foo foo foo foo foo foo foo foo" "foo foo foo foo foo foo foo foo foo foo" "foo foo foo foo foo foo foo foo foo foo" "foo foo foo foo foo foo foo foo foo foo" "foo foo foo foo foo foo foo foo foo foo" "foo foo foo foo foo foo foo foo foo foo" "foo foo foo foo foo foo foo foo foo foo"
顯示功能良好的trim()方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.