0

This is an extension to below question in StackOverflow as I am not understanding the accepted answer.

How do you determine the type of data contained in a string?

If someone could please give a sample code for below case:

I have a String array as below:

String[] myArray = new String[4];
 myArray[0] = "one";
 myArray[1] = "2012-02-25";
 myArray[2] = "12345.58";
 myArray[3] = "1245";

I want something as below:

for(String s:myArray){

 if(s is a number){
   System.out.println("A number!");
 }

 else if(s is a float){
     System.out.println("A float!");
 }

 else if(s is a date){
     System.out.println("A date!");
 }

 else if(s is a text){
     System.out.println("A text!");
 }
}

But I don't know what will come inside the IF conditions to determine the type of data in given String.

Thanks for reading!

Community
  • 1
  • 1
Vicky
  • 16,679
  • 54
  • 139
  • 232
  • Have you considered using regular expressions? – Michael Aquilina Sep 23 '13 at 10:20
  • @MichaelAquilina: I can handle text and numbers using regular expressions.. but what about date ? – Vicky Sep 23 '13 at 10:22
  • @NikunjChauhan If all of your dates are a set format (i.e. YYYY-MM-DD) then you could use a regular expression for those as well. Otherwise the standard methods of converting a formatted String to a Date apply, and you'd need to catch any exceptions. – Anthony Grist Sep 23 '13 at 10:25
  • Try this for date http://stackoverflow.com/questions/7579227/how-to-get-the-given-date-string-formatpattern-in-java – newuser Sep 23 '13 at 10:25
  • The suggestions from AnthonyGrist and newuser are both viable solutions ;) – Michael Aquilina Sep 23 '13 at 11:17

6 Answers6

2

The simplest way to do it is to create the aformentioned methods an simply try to parse the string like (but you have to remember that you cannot tell 100% what datatype a certain pattern is, can be multiple times at once):

public static boolean isANumber(String s) {
    try {
        BigDecimal d = new BigDecimal(s);
        return true;
    } catch (Exception e) {
        return false;
    }
}

public static boolean isAFloat(String s) {
    //same as number, unless you want is a number to 
    //check if it an integer or not
    try {
        BigDecimal d = new BigDecimal(s);
        return true;
    } catch (Exception e) {
        return false;
    }
}

public static boolean isADate(String s) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
    try {
        sdf.parse(s);
        return true;
    } catch (Exception e) {
        return false;
    }
}

public static boolean isAText(String s) {
    //everything could be considered a text
    // unless you want to check that characters are within some ranges
    return true;
}
Claudiu
  • 1,469
  • 13
  • 21
  • +1 Was just writing up the same thing. Addendum: When using those methods, keep in mind the ordering of the tests, i.e., test for integer before testing for float, and test for string last (or rather use it as default). – tobias_k Sep 23 '13 at 10:30
1
public static void main(String[] args) {
    String[] myArray = new String[4];
    myArray[0] = "one";
    myArray[1] = "2012-02-25";
    myArray[2] = "12345.58";
    myArray[3] = "1245";

    for(String str : myArray){
        if(str.matches("[\\d]+")){
            System.out.println(str + " is integer");
        }
        else  if(str.matches("[\\D]+")){
            System.out.println(str + " is word");
        }
        else  if(str.matches("[\\d.]+")){
            System.out.println(str + " is double");
        }
        else  if(str.matches("\\d{4}-\\d{2}-\\d{2}")){
            System.out.println(str + " is date");
        }           

    }

}

Output:

 one is word
 2012-02-25 is date
 12345.58 is double
 1245 is integer
Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
1
  for(String s:myArray){
     if(NumberUtils.isNumber(s)){          //From Apache commons
         double d= Double.valueOf(s);
         if (d==(int)d){
           System.out.println("A number!");
         }else{
           System.out.println("A Float!");
         }
     }else if(isValidDate(s)){
         System.out.println("A date!");
     }else{
         System.out.println("A text!");
     }
  }

Method for valid date check

public static boolean isDateValid(String date) 
{
   try {
          DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
          df.parse(date);
          return true;
   } catch (ParseException e) {
            return false;
   }
}
Ajinkya
  • 22,324
  • 33
  • 110
  • 161
1

Write function like :

private boolean isFloat(String str) {
    try {
        Float.parseFloat(str);
        return true;
    } catch (NumberFormatException) {
        return false;
    }
}

And check the type. Or you can just use apache commons NumberUtils

Mustafa Genç
  • 2,569
  • 19
  • 34
1

One way to do it is by trying to parse the string. Here is an example for one of the types;:

boolean isFloat(String x) {
  try {
    Float.parseFloat(x);
  } catch (Throwable e) {
    return false;
  }
  return true;
}

Note:

As an integer can be parsed a a float you need to test if it is an integer first. So:

if (isInteger(s)) {
   // Integer
else if (isFloat(s)) {
...
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
0

There's no way of defining an array of strings with a declaration of a specific datatype. If you need something like that, use collection like List, e.g. a list of date objects. For strings, you have to programatically determine it by analyzing the data or if you already know what type of data an array of strings or a string contains in your program since you are the one who wrote it, then handle accordingly.

You can create a custom object/class which can take the value and type of data that value represents.

Sajal Dutta
  • 18,272
  • 11
  • 52
  • 74
  • "programatically determine it by analyzing the data" -- yes.. but how ? – Vicky Sep 23 '13 at 10:22
  • @NikunjChauhan You can use regular expressions but if the date for example can be of any format like "Sep 23, 2013", "09/23/2013", or "Sep 23, 13"; I would use a custom class or maybe a map with one property that tells me what type of data the value contains. – Sajal Dutta Sep 23 '13 at 10:27