2

I have int number value and int[] numberArray.
I want to get all values from numberArray that starts with number.

What I am trying to do is

for (int i=0;i<numbers.length;i++){
    if(numberArray[i] "starts with" number){
        System.out.print(numberArray[i]);
     }
}

I also need to use 2 and 3 digit numbers.

Could you help me find a solution for that?

EDIT: Thanks for help, found a solution. At the end code look like that:

String num = String.valueOf(number);
for (int i =0; i< numberArray.size();i++) {
    String anumber = String.valueOf(numberArray[i]);
    if (anumber.startsWith(num)){
        System.out.print(numberArray[i])
    }
}
2
  • 3
    If you want it easy but not performance approved: Convert both the ints to Strings when you want find out if it is true and use String#startsWith Commented Jul 5, 2017 at 12:36
  • @Markus, check all answers before accepting one ;) Commented Jul 5, 2017 at 13:08

6 Answers 6

2

Here is some untested java code. But very bad practice and bad performance... should work for you anyway ^^

public static ArrayList<Integer> getStartingWith(int[] numbers, int key)
{
ArrayList<Integer> matching = new ArrayList<Integer>();

String keyAsString = Integer.toString(key);

for(int i = 0; i < numbers.length; i++)
{
    if(Integer.toString(numbers[i]).startsWith(keyAsString))
        matching.add(numbers[i]);
}
return matching;
}

Take a look at @Andreas answer. Way smarter than mine!!!

Sign up to request clarification or add additional context in comments.

Comments

1

If you don't want to perform any string conversions (while comparing) you can keep it to division.

public void findIfStartingWithDigit(int number){
  int digits = String.valueOf(number).length();
  int tmpNumber;
  for (int i = 0; i < numbers.length; i++){
    tmpNumber = numbers[i];
    while (tmpNumber >= 10*digits){
      tmpNumber = tmpNumber / 10;
    }
    if (tmpNumber == number){
      System.out.println(numbers[i]);
    }
  }
}

Comments

1

A method using streams :

So the method :

  • creates a Stream from the array,
  • converts the int to String
  • to use the startsWith method by filtering and keeping only the element which match,
  • come back to int
  • return a List which contains theses values

public static List<Integer> intStartWidth(int[] values, int start) {
    return Arrays.stream(values)                 //Stream over the array
                 .mapToObj(Integer::toString)    //converts to String
                 .filter(element -> element.startsWith(Integer.toString(start)))  //keep only ones which match
                 .map(Integer::valueOf)          //converts to int
                 .collect(Collectors.toList());  //assembly on a List
 }

//--------------------------------------------------------------------------------

public static void main(String[] args) {
    int[] tab = new int[]{496781, 49872, 3, 49, 76};
    int start = 49;

    List<Integer> result = intStartWidth(tab, start);
    result.forEach(System.out::println);
}

Here how to use it, get an array, a int, call the method and then print all to check if it works

It's clearly easier than iterate by hand over digits or and check each one, here is only existing method

1 Comment

@Markus What is "simpler" in the other one ? Don't misunderstand "new thing" and "complicated things ";) It's easy to understand, using existing method using good performance amelioration
0

Use the number of digits in the number. You can also compare String instead of convert back to int. You should also check the number of digits in the number is not bigger the number of digits in the number from the array

int number;
String stringNumber = String.valueOf(number);

for (int i = 0 ; i < numbers.length ; i++) {
    String num = Integer.toString(numbers[i]);
    if(num.length() >= stringNumber.length() && num.substring(0, stringNumber.length()).equals(stringNumber)) {
        System.out.println(numbers[i]);
    }
}

Comments

0
//...
public static void main(String[] args) {
        // TODO Auto-generated method stub

            String x = "yourstring";
            String pattern = "0123456789";
            String piece  = "";
            StringBuilder num = new StringBuilder();
           if(startsWithDigit(x)){
               for(int i = 0; i < x.length(); i++) {
                    piece = x.substring(i,i+1);             
               if (pattern.indexOf(piece) >0){
                   num.append(piece) ;
               }
               else
                   break;
               }   
          }
           System.out.println(num.toString());
          }
          static boolean startsWithDigit(String s) {
            return Pattern.compile("^[0-9]").matcher(s).find();
    }

Comments

-1
class Test
{ static int firstDigit(int x)
    {
        // Keep dividing by 10 until it is
        // greater than equal to 10
        while(x >= 10)
            x = x/10;
        return x;
    }

    // Driver method
    public static void main(String args[])
    {
        System.out.println(firstDigit(12345));
        System.out.println(firstDigit(5432));
    }
}

2 Comments

Please include some explanation with your code. Code by itself is not a complete answer
This doesn't do what the user ask, definitly not

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.