4

Here is my code

String itemName = "Daily 60k tube";
  String name="";
  if(itemName.matches(".*\\d+.*"))
        {
            itemName = itemName.substring(itemName.indexOf(" ") + 1);
            itemName = itemName.substring(0, itemName.indexOf(" "));
            name = itemName;
        }

I need that 60k as my name in the output. But it is crashing with exception. This is the exception.

java.lang.StringIndexOutOfBoundsException: length=6; regionStart=0; regionLength=-1
                                                                at java.lang.String.startEndAndLength(String.java:298)
                                                                at java.lang.String.substring(String.java:1087)

My output should be "60k". Please help me fixing this issue. Thanks in advance.

Nikhil PV
  • 1,014
  • 2
  • 16
  • 29

4 Answers4

1

You can try this

String itemName = "Daily 60k tube";
String name="";
if(itemName.matches(".*\\d+.*"))
{
    String[] array = itemName.split(" "); // Daily 60k tube
    // array: {"Daily","60k","tube"}
    for (String item : array) {
        if (item.matches(".*\\d+.*")) {
             name = item;
         }
    }
}

EDIT You can also replace the line with this

  (item.matches(".*\\d+.*" + "k")

So it will look like

    String[] array = itemName.split(" "); // Daily 60k tube
    // array: {"Daily","60k","tube"}
    for (String item : array) {
        if (item.matches(".*\\d+.*" + "k") {
             name = item;
         }
    }

Hope this helps

Sanoop Surendran
  • 3,484
  • 4
  • 28
  • 49
1

Try this piece of code

String Name;
String[] array = itemName.split(" ");
for (int i = 0; i < array.length;i++){
    if(Character.isDigit(array[i].charAt(0)))
    {
        Name = array[i];
        break;
    }

}

Hope this helps. Happy Coding :)

Shrenik Shah
  • 1,900
  • 1
  • 11
  • 19
  • if you found it helpful to you and it resolves what you want kindly mark this as answer so that it can be useful to others as well. – Shrenik Shah Aug 03 '16 at 10:22
0

I think this will helps you.

 int i=itemName.indexOf(" ") + 1;
    itemName = itemName.substring(i);
    i=itemName.indexOf(" ");
    itemName = itemName.substring(0,i);
    name = itemName;
Shanto George
  • 994
  • 13
  • 26
0

Try this way:

private static String getResult(String itemName) {
        String[] result = itemName.split(" ");
        for (String i : result) {
            if (Character.isDigit(i.charAt(0))) {
                return i;
            }
        }
        return null;
    }
xxx
  • 3,315
  • 5
  • 21
  • 40