【问题标题】:how to parse a string containing integers and numbers如何解析包含整数和数字的字符串
【发布时间】:2013-12-08 21:53:34
【问题描述】:

假设输入是 C3F5G10

我知道一个事实,每个其他偶数都是一个字符,每个奇数都是一个整数。但是,这仅在整数是单个数字时才有效。在这种情况下它不是,因为 10 被读取为 2 个单独的元素。

我该如何解决这种情况?基本上输出只会打印整数旁边的字符数

CCCFFFFFGGGGGGGGGG

 public static String translate(String formatStr) {
        char [] array = formatStr.toCharArray();
    char [] carray = new char[array.length/2];
    char [] narray = new char[array.length/2];
    StringBuilder build1 = new StringBuilder();



    int m = 0;
    for(int i  = 0; i<carray.length; i++){
        carray[i] = array[m];
        m+=2;
    }
    int l =1;
    for(int i = 0; i<narray.length; i++){
        narray[i] = array[l];
        l+=2;
    }



    for(int i = 0; i < carray.length; i++){
        String number = Character.toString(narray[i]);
        for(int j=0;j<Integer.parseInt(number);j++){
            build1.append(carray[i]);   
        }

        }

    return build1.toString();
}

【问题讨论】:

  • 哦,伙计,我刚看到一个这样的问题。就像你们都来这里寻求编程帮助一样。
  • 我想一个相关的问题是“你试过什么?”
  • 我想你们有同样的功课stackoverflow.com/questions/20171289/…
  • @SimplyPanda:学期结束了。他们的编程作业都需要帮助。
  • 有趣,这实际上是我们今天在学校举办的编码比赛。现在结束了,我自己解决了一些问题

标签: java string parsing


【解决方案1】:

我坚信,人学习某件事的唯一方法就是自己动手,所以我将为您提供一些见解,您将自己编写代码。
保留一个保存临时号码的变量,比如num。将字符串从左到右读取到名为currentChar 的变量中,逐个字符地读取。如果当前字母是字符,那么您知道需要打印什么;将其保存在变量charToPrint 中。如果是数字,则进行以下更改:num = num * 10 + &lt;convert-your-character-to-integer&gt; currentChar。下次遇到该字符时,可以打印上一次找到的字符,charToPrintnum 次。之后将 0 分配给 num。
希望对您有所帮助。

【讨论】:

    【解决方案2】:

    试试,

      public static String translate(String word) {
        StringBuilder res = new StringBuilder();
        char let = ' ';
        String num = "";
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            if (Character.isDigit(ch)) {
                num += ch;
            } else if (Character.isLetter(ch)) {
                if (num.length() > 0) {
                    for (int j = 0; j < Integer.parseInt(num); j++) {
                        res.append(let);
                    }
                }
                let = ch;
                num = "";
            }
        }
        if (num.length() > 0) {
            for (int j = 0; j < Integer.parseInt(num); j++) {
                res.append(let);
            }
        }
        return res.toString();
      }
    

    【讨论】:

      【解决方案3】:

      这是我的解决方案。似乎工作。来自int tmp=0 的行是您感兴趣的。这就是我如何处理一个字符后的多个数字。

      import java.io.PrintWriter;
      import java.util.Scanner;
      
      public class QuestionTwo {
        public static void main(String[] args) {
          PrintWriter out = new PrintWriter(System.out);
          Scanner sc = new Scanner(System.in);
      
          char[] input = sc.nextLine().trim().toCharArray();
      
          StringBuilder ans = new StringBuilder("");
          int i = 0;
          while (true) {
            if (i > input.length - 1)
              break;
            // Has to be a character.
            char c = input[i];
            i++;
            int tmp = 0;
            while (i < input.length && Character.isDigit(input[i])) {
              tmp *= 10;
              tmp += input[i] - '0';
              i++;
            }
            while (tmp-- > 0)
              ans.append(c);
          }
          out.println(ans.toString());
          out.close();
          sc.close();
        }
      }
      

      【讨论】:

        【解决方案4】:

        看看这个实现。希望对你有帮助。

        public class Test {
        
        public static void main(String[] args) {
        
            String input = "C3F5G10";
            StringBuilder sBuilderChar = new StringBuilder();
            String digit = "";
            for (int i = 0; i < input.length(); i++) {
                if (isCharacter(input.charAt(i))) {
                    int k = i;// store index of character.
                    // loop until the next character is not encountered
                    // form a string of all the digits sandwiched between two
                    // characters
                    while (k < input.length() - 1 && isDigit(input.charAt(k + 1))) {
                        digit = digit + input.charAt(k + 1);
                        k++;
                    }
                    // convert the digit string to number
                    int n = Integer.parseInt(digit);
                    // append the character the number of times calculated
                    // previously
                    for (int j = 0; j < n; j++) {
                        sBuilderChar.append(input.charAt(i));
                    }
                    // skip all the digits and move to next character
                    // i.e. current index + the length of digit obtained
                    i = i + digit.length();
                    // empty the digit string
                    digit = "";
                }
        
            }
            // print the string formed to console
            System.out.println(sBuilderChar);
        
        }
        
        public static boolean isDigit(char c) {
            // digits are in the range [48,57] in ASCII code
            return c >= 48 && c <= 57;
        }
        
        public static boolean isCharacter(char c) {
            // if not digit then 'c' is a character
            return !isDigit(c);
        }
        
        }
        

        【讨论】:

        • 它应该打印CCCFFFFFGGGGGGGGGG 而不是CFG
        • @Masud 是的,我已经纠正并发布了正确的答案。感谢您指出
        【解决方案5】:

        如果你想使用正则表达式,那么这里有一个方法...

         public static String translate(String formatStr) {
            StringBuilder result = new StringBuilder();
            //make sure it really contains just alphanumeric
            if(formatStr.matches("^[a-zA-Z0-9]*$")) {
                String alphas[] = removeInvalid(formatStr.split("[0-9]"));
                String numerics[] = removeInvalid(formatStr.split("[a-zA-Z]"));
                int alphaPointer = 0;
                for(String num: numerics) {
                    int iterator = Integer.valueOf(num);
                    for(int i=0; i< iterator; i++) {
                        result.append(alphas[alphaPointer]);
                    }
                    alphaPointer++;
                }
            }
            return result.toString();
        
        }
        
        /*
         * Remove empty results from the regex split 
         */
        private static String[] removeInvalid(String[] values) {
            ArrayList<String> list = new ArrayList<String>();
            for(String value: values) {
                if(value.matches("\\d+") || value.matches("\\w+"))
                    list.add(value);
            }
            String[] valids = new String[list.size()];
            return list.toArray(valids);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-30
          • 1970-01-01
          相关资源
          最近更新 更多