1

I have a string in format AB123. I want to split it between the AB and 123 so AB123 becomes AB 123. The contents of the string can differ but the format stays the same. Is there a way to do this?

Mac
  • 131
  • 1
  • 7
  • 7
    It's unclear what the important characteristics of your format are - two characters then three characters? Uppercase letters then digits? Depending on what the format is, you could either do it absolutely based on length or maybe use a regular expression to extract the relevant parts. – jonrsharpe Apr 11 '19 at 11:01
  • 1
    Sorry, I am very new to programming. It is 2 characters, case can either be lower or uppercase then followed by 3 digits. – Mac Apr 11 '19 at 11:02
  • 1
    So you just need to insert a space between char [1] and char [2]? – khelwood Apr 11 '19 at 11:02
  • I need a space between the two letter and the 3 numbers like: AB 123 – Mac Apr 11 '19 at 11:04
  • Possible duplicate of [Splitting a string at a particular position in java](https://stackoverflow.com/questions/28419586/splitting-a-string-at-a-particular-position-in-java) – Syed Mehtab Hassan Apr 11 '19 at 11:06
  • 1
    Hi Mac, next time you post a question please post an [MCVE](https://stackoverflow.com/help/mcve) or [SSSCE](https://acronyms.thefreedictionary.com/SSSCE) to show us what you have tried and what you are stuck with. This will help you get better help sooner – Dan Apr 11 '19 at 13:26

6 Answers6

8

Following up with the latest information you provided (2 letters then 3 numbers):

myString.subString(0, 2) + " " + myString.subString(2)

What this does: you split your input string myString at the 2nd character and append a space at this position.

Syed Mehtab Hassan
  • 1,297
  • 1
  • 9
  • 23
belka
  • 1,480
  • 1
  • 18
  • 31
  • @Mac since this covers your needs, would you accept the answer? – belka Apr 11 '19 at 12:05
  • 1
    Please don't ask users to accept your answer. Several answers here meet the criteria and could also be accepted. Also the user appears to have been offline since you posted your answers so I'm sure they will accept an answer when they come back on and find their question has been answered – Dan Apr 11 '19 at 13:23
  • @Dan Not specifically asking to accept *my* answer, just the answer that fits his needs. – belka Apr 11 '19 at 13:24
4

Explanation: \D represents non-digit and \d represents a digit in a regular expression and I used ternary operation in the regex to split charter to the number.

  String string = "AB123";
  String[] split = string.split("(?<=\\D)(?=\\d)");
  System.out.println(split[0]+" "+split[1]);
  • This answer works but is very generic and is an overkill to your problem. Regexes (regular expressions) are nice when working with variable format but yours is already fixed. Plus, regexes are slower than a simple split. – belka Apr 11 '19 at 11:09
  • @TimBiegeleisen, I have added some explanation. – Rakesh Mothukuri Apr 11 '19 at 11:20
1

Try

String a = "abcd1234";
int i;
for(i = 0; i < a.length(); i++){
    char c = a.charAt(i);
    if( '0' <= c && c <= '9' )
        break;
}
String alphaPart = a.substring(0, i);
String numberPart = a.substring(i);

Hope this helps

nullPointer
  • 4,419
  • 1
  • 15
  • 27
Krupal SG
  • 31
  • 6
1

Although I would personally use the method provided in @RakeshMothukur's answer, since it also works when the letter or digit counts increase/decrease later on, I wanted to provide an additional method to insert the space between the two letters and three digits:

String str = "AB123";
StringBuilder sb = new StringBuilder(str);
sb.insert(2, " "); // Insert a space at 0-based index 2; a.k.a. after the first 2 characters
String result = sb.toString(); // Convert the StringBuilder back to a String

Try it online.

Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135
1

Here you go. I wrote it in very simple way to make things clear.

What it does is : After it takes user input, it converts the string into Char array and it checks single character if its INT or non INT. In each iteration it compares the data type with the prev character and prints accordingly.

Alternate Solutions

1) Using ASCII range (difficulty = easy)

2) Override a method and check 2 variables at a time. (difficulty = Intermediate)

import org.omg.CORBA.INTERNAL;

import java.io.InputStreamReader;
import java.util.*;
import java.io.BufferedReader;


public class Main {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        char[] s = br.readLine().toCharArray();
        int prevflag, flag = 0;
        for (int i = 0; i < s.length; i++) {
            int a = Character.getNumericValue(s[i]);
            String b = String.valueOf(s[i]);
            prevflag = flag;
            flag = checktype(a, b);
            if ((prevflag == flag) || (i == 0))
                System.out.print(s[i]);
            else
                System.out.print(" " + s[i]);
        }
    }

    public static int checktype(int x, String y) {
        int flag = 0;
        if (String.valueOf(x).equals(y))
            flag = 1; // INT
        else
            flag = 2; // non INT
        return flag;

    }
}
0

I was waiting for a compile to finish before heading out, so threw together a slightly over-engineered example with basic error checking and a test.

import java.text.ParseException;
import java.util.LinkedList;

public class Main {

    static public class ParsedData {
        public final String prefix;
        public final Integer number;

        public ParsedData(String _prefix, Integer _number) {
            prefix = _prefix;
            number = _number;
        }

        @Override
        public String toString() {
            return prefix + "\t" + number.toString();
        }

    }

    static final String TEST_DATA[] = {"AB123", "JX7272", "FX402", "ADF123", "JD3Q2", "QB778"};

    public static void main(String[] args) {
        parseDataArray(TEST_DATA);
    }

    public static ParsedData[] parseDataArray(String[] inputs) {
        LinkedList<ParsedData> results = new LinkedList<ParsedData>();
        for (String s : TEST_DATA) {
            try {
                System.out.println("Parsing: " + s);
                if (s.length() != 5) throw new ParseException("Input Length incorrect: " + s.length(), 0);
                String _prefix = s.substring(0, 2);
                Integer _num = Integer.parseInt(s.substring(2));
                results.add(new ParsedData(_prefix, _num));
            } catch (ParseException | NumberFormatException e) {
                System.out.printf("\"%s\", %s\n", s, e.toString());
            }
        }
        return results.toArray(new ParsedData[results.size()]);
    }
}
D'Nabre
  • 2,226
  • 16
  • 13