search

Home  >  Q&A  >  body text

string - How to operate java string to achieve such effect

For example, there are some strings like this:
H3C18,
H301C108
How to separate it into
H3 and C18,
H301 and C108

伊谢尔伦伊谢尔伦2743 days ago574

reply all(3)I'll reply

  • 黄舟

    黄舟2017-05-17 10:01:34

    Regular expressions seem to meet the needs

    import java.util.LinkedList;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Test {
        public static void main(String[] args) {
            System.out.println(tokens("H3C18"));
            System.out.println(tokens("H301C108"));
        }
    
        private static final Pattern PATTERN = Pattern.compile("[a-zA-Z]\d+");
    
        public static List<String> tokens(String text) {
            List<String> result = new LinkedList<>();
            Matcher matcher = PATTERN.matcher(text);
    
            while (matcher.find()) {
                result.add(matcher.group(0));
            }
    
            return result;
        }
    }

    Output

    [H3, C18]
    [H301, C108]

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-17 10:01:34

    The rule is "C", just make a fuss about it, it's not difficult, just think about it

    reply
    0
  • PHP中文网

    PHP中文网2017-05-17 10:01:34

    Please don’t be a douchebag. Such problems are all problems that can be solved by checking the API.
    Think more and make more progress

    The idea is to cut the string and find the index corresponding to the character.

    reply
    0
  • Cancelreply