【问题标题】:Parse String and Replace Letters Java解析字符串并替换字母 Java
【发布时间】:2012-01-22 08:57:06
【问题描述】:

在输入时我有一些字符串:“今天下雪知道”,这里我有 3 个单词,所以我必须这样解析它们:我必须将每个字符与所有其他字符进行比较,并总结这些字符有多少相同的字符单词 have ,例如“o”字母将是 2(来自“today”和“snowing”)或“w”字母将是 2(来自“know”和“snowing”)。之后,我必须用字母的数字(转换为字符格式)替换这些字符。结果应该是“13111 133211 1332”。

我做了什么?

首先我把一些单词录下来

    public void inputStringsForThreads () {

       boolean flag;

            do {

    // will invite to input 
                stringToParse = Input.value();   

                try {

                flag = true;

    // in case that found nothing , space , number and other special character , throws an exception
                if (stringToParse.equals("") | stringToParse.startsWith(" ") | stringToParse.matches(".*[0-9].*") | stringToParse.matches(".*[~`!@#$%^&*()-+={};:',.<>?/'_].*"))

                    throw new MyStringException(stringToParse);

                else  analizeString(stringToParse);    
            }

            catch (MyStringException exception) {

                stringToParse = null;
                flag = false;
                exception.AnalizeException();  
            } 
          }
            while (!flag);
}

我消除了单词之间的空格,并且从这些单词中只剩下一个

   static void analizeString (String someString) {

// + sign treat many spaces as one
      String delimitator = " +";

// words is a String Array
      words = someString.split(delimitator);

// temp is a string , will contain a single word
      temp = someString.replaceAll("[^a-z^A-Z]","");


         System.out.println("=============== Words are : ===============");
      for (int i=0;i<words.length;i++)
          System.out.println((i+1)+")"+words[i]);
    }  

所以我尝试将每个单词(每个单词都分成字母)与所有单词中的所有字母进行比较,但我不知道如何计算相同字母的数量,然后用每个字母的正确数量替换字母? ??有什么想法吗?

// this will containt characters for every word in part 
         char[] motot  =   words[id].toCharArray();

// this will containt all characters from all words     
         char[] notot = temp.toCharArray();


   for (int i =0;i<words[i].length();i++)

               for (int j=0;j<temp.length ;j++)

               {
                   if (i == j) {

                       System.out.println("Same word");

                   }

                   else   if (motot[i] == notot[j] ) {

                       System.out.println("Found equal :"+lol[i]+" "+lol1[j]);

                   }}

【问题讨论】:

  • 试试HashMap&lt;Character,Integer&gt;
  • 大写/小写字母呢(出于计数目的,它们是否被认为是相同的字符)?

标签: java string char


【解决方案1】:

对于计数,您可能需要使用Map&lt;Character, Integer&gt; counter,例如java.util.HashMap。如果使用来自计数器的特定键(字符)获取值(整数)不是“非空”,那么您的值 ++(利用自动装箱)。否则在计数器中添加一个新条目 (char, 1)。

那么用数字替换字母应该相当容易。

【讨论】:

  • +1,不过,更简单的方法可能是使用大小为 26 的数组,并在迭代结束时增加 index = character - 'a'...处的值,你会数数。
【解决方案2】:

最好像这样使用模式匹配:

最初..

private Matcher matcher; 
Pattern regexPattern = Pattern.compile( pattern ); 
matcher = regexPattern.matcher("");  

用于匹配多个模式。

private final String[] patterns = new String [] {/* instantiate patterns here..*/} 
private Matcher matchers[]; 
for ( int i = 0; i < patterns.length; i++) {
Pattern regexPattern = Pattern.compile( pattern[i] ); 
matchers[i] = regexPattern.matcher(""); 

}

然后匹配模式..你这样做..

if(matcher.reset(charBuffer).find() ) {//matching pattern.} 

用于多个匹配器检查。

for ( int i = 0; i < matchers.length; i++ ) if(matchers[i].reset(charBuffer).find() ) {//matching pattern.} 

不要使用字符串匹配,效率不高。

始终使用 CharBuffer 而不是 String。

【讨论】:

    【解决方案3】:

    这是一些 C# 代码(与 Java 相当相似):

    void replace(string s){
    
        Dictionary<char, int> counts = new Dictionary<char, int>();
    
        foreach(char c in s){
            // skip spaces
            if(c == ' ') continue;
    
            // update count for char c
            if(!counts.ContainsKey(c)) counts.Add(c, 1);
            else counts[c]++;
        }
    
        // replace characters in s
        for(int i = 0; i < s.Length; i++) 
            if(s[i] != ' ') 
                s[i] = counts[s[i]];
    }
    

    注意第二个循环中的不可变字符串。可能想使用某种StringBuilder

    【讨论】:

      【解决方案4】:

      这是一个仅适用于小写字符串的解决方案。可怕的可怕代码,但我试图看看我能用几行代码编写解决方案。

      public static String letterCount(String in) {
        StringBuilder out = new StringBuilder(in.length() * 2);
        int[] count = new int[26];
        for (int t = 1; t >= 0; t--)
          for (int i = 0; i < in.length(); i++) {
            if (in.charAt(i) != ' ') count[in.charAt(i) - 'a'] += t;
            out.append((in.charAt(i) != ' ') ? "" + count[in.charAt(i) - 'a'] : " ");
          }
        return out.substring(in.length());
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-19
        • 2012-05-31
        • 2021-01-27
        • 1970-01-01
        • 2015-12-09
        • 1970-01-01
        相关资源
        最近更新 更多