Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
28 views

Java Beginner Guide

The document describes a function that accepts a character array, start position, and length. It should return a substring of the given length starting from the start position, or null if the start/length are invalid. It provides examples of expected returns for different inputs. A solution is given that implements the function by checking for invalid start/length, creating a substring array, and copying characters from the original array.

Uploaded by

Shafiqul Islam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Java Beginner Guide

The document describes a function that accepts a character array, start position, and length. It should return a substring of the given length starting from the start position, or null if the start/length are invalid. It provides examples of expected returns for different inputs. A solution is given that implements the function by checking for invalid start/length, creating a substring array, and copying characters from the original array.

Uploaded by

Shafiqul Islam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

3.

Write a function that accepts a character array, a zero-based start position and a
length. It should return a character array containing containing lengthcharacters
starting with the startcharacter of the input array. The function should do error
checking on the start position and the length and return null if the either value is not legal.
The function signature is:
char[ ] f(char[ ] a, int start, int len)

Examples

if input parameters are return


{‘a’, ‘b’, ‘c’}, 0, 4 null
{‘a’, ‘b’, ‘c’}, 0, 3 {‘a’, ‘b’, ‘c’}
{‘a’, ‘b’, ‘c’}, 0, 2 {‘a’, ‘b’}
{‘a’, ‘b’, ‘c’}, 0, 1 {‘a’}
{‘a’, ‘b’, ‘c’}, 1, 3 null
{‘a’, ‘b’, ‘c’}, 1, 2 {‘b’, ‘c’}
{‘a’, ‘b’, ‘c’}, 1, 1 {‘b’}
{‘a’, ‘b’, ‘c’}, 2, 2 null
{‘a’, ‘b’, ‘c’}, 2, 1 {‘c’}
{‘a’, ‘b’, ‘c’}, 3, 1 null
{‘a’, ‘b’, ‘c’}, 1, 0 {}
{‘a’, ‘b’, ‘c’}, -1, 2 null
{‘a’, ‘b’, ‘c’}, -1, -2 null
{}, 0, 1 null
 
Solution:
static char[] a3(char[] a, int start, int length)
{
if (length < 0 || start < 0 || start+length-1>=a.length)
{
return null;
}

char[] sub = new char[length];


for (int i=start, j=0; j<length; i++, j++)
{
sub[j] = a[i];
}

return sub;
}

You might also like