java - Java 解析字符串并替换字母

标签 java string char

在输入时我有一些字符串:“今天下雪知道”,这里我有3个单词,所以我必须这样解析它们:每个字符我必须与所有其他字符进行比较,并总结这些字符有多少个相同的字符单词有,例如“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]);

                   }}

最佳答案

为了计数,您可能需要使用 Map<Character, Integer> counter喜欢 java.util.HashMap 。如果使用计数器中的特定键(字符)获取值(整数)为“非空”,则您的值++(利用自动装箱)。否则在计数器中放入一个新条目(char,1)。

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

关于java - Java 解析字符串并替换字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8540827/

相关文章:

java - 用 Java 中的流 API 调用替换 for-each 循环

java - 我到底什么时候应该使用 StringBuilder 而不是 String

c++ - 在 C++ 中将 char 数组解压为字符串

C fwrite() 写入的字符数量加倍

java - 将空格的下一个字符设为大写

Java JApplet 在移动旧矩形后不会将其删除

java - 使用 RequestBody 的 POST 请求不起作用

javascript - 按索引位置删除部分字符串

c++ - 算法识别字符串匹配散列和无误报

c - C中使用指针的二维字符串排列