簡體   English   中英

如果有的話,在第二個空格后刪除字符串中的所有內容

[英]Remove everything in a string after a second space if there is one

讓我們說我有這樣的文字: Thundering Blow I 我需要的東西讓它看起來像Thundering Blow般的Thundering Blow - 刪除字符串末尾的羅馬數字。

我已經嘗試了trim()和一些substring()方法,但它們都繼續返回: Thundering Blow I回到我身邊。 也許這可能一個后刪除一切I在字符串中? 也可以,但我似乎無法找到解決問題的方法。

你需要這個,在第二個空格后刪除所有字符

String s = "Thundering Blow I";
int k = s.indexOf(" ", s.indexOf(" ") + 1);
String res = s.substring(0,k);
System.out.println(res);
String newStr = s.substring(0, s.lastIndexOf(" "));

這是整個代碼:

String s = "ThunderingI";
s = s.trim();
int ind = s.lastIndexOf(" ");
if (ind > 0) {
    s = s.substring(0, ind).trim();
}
System.out.println(s);

您可以拆分字符串然后連接索引0和1的新字符串。最簡單的解決方案:) ..

String[] tempArray = orgStr.split(" ");
String newStr = tempArray[0] + " " + tempArray[1];

你可以試試這個。

        String a = "Thundering Blow I";
        String[] b = a.split(" ");
        System.out.println(b[0]+" "+b[1]);

這將從字符串末尾刪除單個羅馬數字(如果存在):

String input = "Thundering Blow returning MMXVI";
input = input.replaceAll("\\s[CDILMVX]*$", "");

如果您想知道, MMXVI是2016年的羅馬數字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM