Compares a null terminated substring from an array of bytes. - Java java.lang

Java examples for java.lang:byte Array to String

Description

Compares a null terminated substring from an array of bytes.

Demo Code

/**/*from   ww  w. j  av  a2 s.  co  m*/
 *******************************************************************************
 * Copyright (C) 1996-2004, International Business Machines Corporation and    *
 * others. All Rights Reserved.                                                *
 *******************************************************************************
 */
//package com.java2s;

public class Main {


    /**
     * Compares a null terminated substring from an array of bytes.
     * Substring is a set of non-zero bytes starting from argument start to the 
     * next zero byte. if the first byte is a zero, the next byte will be taken as
     * the first byte.
     * @param str string to compare
     * @param array byte array
     * @param strindex index within str to start comparing
     * @param aindex array index to start in byte count
     * @return the end position of the substring within str if matches otherwise 
     *         a -1
     */
    static int compareNullTermByteSubString(String str, byte[] array,
            int strindex, int aindex) {
        byte b = 1;
        int length = str.length();

        while (b != 0) {
            b = array[aindex];
            aindex++;
            if (b == 0) {
                break;
            }
            // if we have reached the end of the string and yet the array has not 
            // reached the end of their substring yet, abort
            if (strindex == length
                    || (str.charAt(strindex) != (char) (b & 0xFF))) {
                return -1;
            }
            strindex++;
        }
        return strindex;
    }
}

Related Tutorials