2013-10-19 22 views
1

我正在嘗試製作一個Minecraft Bukkit插件,並且它涉及製作井號標籤等。我擁有它,所以當你做#hashtag-goes-here它會突出顯示它。唯一的問題是,你必須在它之後有一個詞(有一個空格)才能起作用。這是到目前爲止我的代碼:Java - 單詞結尾處的循環結束

  try{ 
       for(int i = index; i < message.length(); i++){ 
        String str = Character.toString(message.charAt(i)); 
        String sbString = sb.toString().trim(); 
        System.out.println(sbString); 
        if(str.equals(" ")){ 
         str.replace(str, str + ChatColor.RESET); 
         String hName = sb.toString().replaceFirst("#", "").trim(); 
         String newMessage = message.replaceAll("#", ChatColor.AQUA + "#").replace(str, ChatColor.RESET + str); 
         event.setMessage(newMessage); 
         logHashtag(event.getPlayer(), event.getMessage(), hName); 
         break; 
        }else{ 
         sb.append(str); 
        } 
       } 
      }catch(Exception e){ 
       throw new HashtagException("Failed to change hashtag colors in message!"); 
      } 

編輯:(已經回答了像,去年,我知道,這是爲了讓誰看這個人知道我是問)我的問題是,這樣它可以在所有情況下的工作,包括hashtag可以在附加感謝發現後,到halfbit幫助我:)

+3

並且您的問題是什麼? –

+0

如果只有一個單詞,我需要它工作 – DonkeyCore

回答

1

如果你想找到一個文本字符串,並強調他們,那麼正則表達式是非常有用的。您可能會使用類似於以下代碼:

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class HashTagColorizer { 

    public static void main(String[] args) { 
     String AQUA = "<AQUA>", RESET = "<RESET>"; 
     String message = "Aaa #hashtag-goes-here bbb #another-hashtag ccc"; 
     Pattern pattern = Pattern.compile("#([A-Za-z0-9-]+)"); 
     Matcher matcher = pattern.matcher(message); 
     StringBuilder sb = new StringBuilder(message.length()); 
     int position = 0; 
     while (matcher.find(position)) { 
      sb.append(message.substring(position, matcher.start())); 
      sb.append(AQUA); 
      System.out.println("event for " + matcher.group(1)); 
      sb.append(matcher.group().substring(1)); 
      sb.append(RESET); 
      position = matcher.end(); 
     } 
     sb.append(message.substring(position)); 
     System.out.println(sb); 
     // Aaa <AQUA>hashtag-goes-here<RESET> bbb <AQUA>another-hashtag<RESET> ccc 
    } 

} 
0

而不是做在ifsb你的邏輯,你就在別人的str(或sbstr,但是您將在已經處理的sb的部分中重複大量處理essed)。

不客氣。

BTW:

str.replace(str, str + ChatColor.RESET); 

什麼也不做,因爲String實例是不可變的