2015-11-13 23 views
1

如果我們有如何用點之前的單詞替換字符串中的點('。')?

String x="Hello.World"; 

我期待以取代'.'"Hello",成具有:"HelloHelloWorld"

的問題是,如果我有:

String Y="Hello.beautiful.world.how.are.you;" 

的答案必須是"HelloHellobeautifulbeautifulworldworldhowhowareareyouyou"

請記住,我不能使用數組。

+1

遍歷字符串。開始構建「最後看到的單詞」字符串,並且每當你看到一個'.'時,吐出「最後看到的單詞」,然後再次開始構建。 –

+3

你嘗試過什麼嗎? – Reimeus

+0

您是否試圖將點轉換爲前面的字符串? – Hua

回答

1

想想像指針問題一樣的問題。你需要保持一個正在運行的pointer,指向你查看的最後一個地方(我的代碼中有firstIndex),還有一個指向你當前位置的指針(在我的代碼中爲nextIndex)。調用subString()(在第一次出現之後添加1到firstIndex,因爲我們不需要捕獲「。」),將它附加到新字符串兩次,然後更改指針。有可能是一個更優雅的解決方案,但是,這能夠完成任務:

String Y="Hello.beautiful.world.how.are.you"; 
    int firstIndex=0; 
    int nextIndex=Y.indexOf(".",firstIndex); 

    String newString = ""; 
    while(nextIndex != -1){ 
     newString += Y.substring(firstIndex==0 ? firstIndex : firstIndex+1, nextIndex); 
     newString += Y.substring(firstIndex==0 ? firstIndex : firstIndex+1, nextIndex); 
     firstIndex=nextIndex; 
     nextIndex=Y.indexOf(".", nextIndex+1); 
    } 

    System.out.println(newString); 

輸出:

HelloHellobeautifulbeautifulworldworldhowhowareare 
+0

LGTM,但你應該(可能)改變它以追加最後一個點後面的字符串。但是,這個問題並不是非常具體。 – Lykos

3

我認爲你可以使用正則表達式替代來實現這一點。在正則表達式中,您可以使用所謂的「捕獲組」。你匹配一個詞加上你的正則表達式的一個點,然後你用匹配的詞兩倍來替換它。

// Match any number of word characters plus a dot 
Pattern regex = Pattern.compile("(\\w*)\\."); 

Matcher regexMatcher = regex.matcher(text); 

// $1 is the matched word, so $1$1 is just two times that word. 
resultText = regexMatcher.replaceAll("$1$1"); 

請注意,我沒有嘗試它,因爲它可能會帶我半小時來設置Java環境等,但我非常有信心,它的作品。

+0

如果他不能使用數組,我會認爲正則表達式也不存在。 –

+0

我知道有這種可能性,但爲了完整性,我想提一提。要麼他可以使用它們,那麼這應該是一個很好的答案,否則,他可以更新問題並忽略它。 – Lykos

-2

這是我有:

public String meowDot(String meow){ 
    int length = meow.length(); 
    String beforeDot = ""; 
    String afterDot; 
    char character; 
    for(int i=0; i < length; i++){ 
     character = meow.charAt(i); 
     if (i < largo - 1 && character == '.'){ 
      beforeDot += meow.substring(0, i) + meow.substring(0, i); 
      afterDot = meow.substring(i, length); 
      meow = afterDot; 
     } else if(i == length - 1 && character != '.'){ 
      afterDot += meow + meow; 
     }   
    } 
    return beforeDot; 
} 
+1

您應該在原始帖子中發佈您的嘗試。 –

+0

這個算法有一個小問題。你可以把點變成點後的東西,但是你不會重置變量'i',即你繼續在錯誤的位置。 – Lykos

+0

@JackmeriusTacktheritrix用戶可能會回答自己的問題,即使它不起作用。如果他們更好 –

相關問題