2015-05-12 50 views
-6

我正在嘗試編寫一個程序,該程序接受一個輸入,並將每個第5個字符替換爲X(計數空格)。 例如: 輸入:「你好,我的名字是馬里奧」 outpu:「我hellX習Xame maXio」替換輸入的每個第5個字符(空格計數)

我只是管理更換特定的字母,e.g每一個「M」字母。

任何幫助?

+0

您可以將字符串轉換爲char型數組和遍歷它,同時通過指數 –

+0

改變每5個字符如果我們能看到你的代碼,我們就能夠指出爲什麼它不像你打算的那樣工作。 – CodeNewbie

+0

[插入每個(x)JAVA空間,使用正則表達式]的可能的重複項(http://stackoverflow.com/questions/29335312/inserting-a-space-every-x-java-using-regular-expression) –

回答

0

下面是代碼爲您提供:

String test = "hello my name is mario"; 

    String result = ""; 
    int c = 1; 
    for (int i = 0; i < test.length(); i++) { 
     if (c++==5) { 
      result += "X"; 
      c = 1; 
     } else { 
      result += test.charAt(i); 
     } 
    } 
    System.out.println("result = " + result); 
+0

爲什麼(C++ == 5)而不是(c%5 == 0)?它快嗎? –

+0

如果速度更快但人類可讀性更好 – chokdee

1

如果你不關心哪個角色是你可以使用正則表達式的每個第五名的位置。

String input = "hello my name is mario"; 
String output = input.replaceAll("(....).", "$1X"); 
System.out.printf("input : %s%noutput: %s%n", input, output); 

輸出

input : hello my name is mario 
output: hellX my Xame Xs maXio 
+0

'(。{4})''更短:) – TheLostMind

+0

@TheLostMind我相信你同意我的觀點,在這種情況下,如果我們用'(....)。'或'(。{4})'匹配。 ;-)或者你的意思是我忽略的其他東西。 (也許我們的帖子之間有一些重疊。) – SubOptimal

+0

沒有。你的正則表達式看起來不錯。我只是想*縮短它:) – TheLostMind

相關問題