DUE In 5 Hours!!!!!!! Need this done ASAP! Use this skeleton class to complete i
ID: 3804444 • Letter: D
Question
DUE In 5 Hours!!!!!!!
Need this done ASAP!
Use this skeleton class to complete it!
https://codeshare.io/2jAjKA
You will be writing some of the methods in the Java String class API. You are not using the methods, you are writing them.
The only methods from the API you are allowed to use are:
From String class: From Scanner class- all methods
constructors
toCharArray( )
toString( )
You may use the .length field that all arrays in Java have.
Implement the following methods; you can look at the API to see what they do.
MyString(String str)
char charAt(int index)
int compareTo(MyString anotherMyString)
int compareToIgnoreCase(MyString anotherMyString)
MyString concat(MyString str)
boolean endsWith(MyString suffix)
boolean equals(MyString anotherMyString)
boolean equalsIgnoreCase(MyString anotherMyString)
int indexOf(char ch)
int indexOf(char ch, int fromIndex)
int lastIndexOf(char ch)
int length( )
MyString replace(char oldChar, char newChar)
boolean startsWithString(MyString prefix)
MyString substring(int beginIndex)
MyString substring(int beginIndex, int endIndex)
MyString toLowerCase( )
MyString toUpperCase( )
String toString( )
For extra credit you may implement other methods in the Java String class.
suggested:
MyString replaceAll(MyString str, MyString replacement)
int indexOf(MyString str)
int indexOf(MyString str, int fromIndex)
boolean contains(MyString s)
Name your class MyString.
The fields should be the original String and an array of chars.
Write a constructor method that accepts a String as a parameter and initializes the two fields.
Write a method for each of the API String methods listed above. Do not use the String API except as noted above.
Write a driver class that reads in a line of text from the user. Then test each of the methods you have written. Be sure to print a clear explanation of the test and the results.
ie: Original string is: test
Result from call to toUpperCase: TEST
You will only get credit for the methods you write AND demonstrate a test result.
Post questions on the discussion board. The instructors will determine if the question is general enough to answer. Never post your code. This is a test, not an exercise only.
Updated information (v2):
The MyString class is immutable (like the normal String class). So methods that “modify” the string will create and return a new MyString object.
You need not be concerned about error handling; assume all input is valid.
We changed most methods that took Strings to now take MyStrings as arguments. We included return values in our method list above.
Explanation / Answer
// MyString.java
public class MyString
{
private String original; // do not use this field
private char[] sequence;
public MyString(String start)
{
this(start.toCharArray());
}
public MyString(char[] inSequence)
{
original = new String(inSequence);
this.sequence = new char[inSequence.length];
for (int k = 0; k < sequence.length; k++)
{
this.sequence[k] = inSequence[k];
}
}
public MyString(MyString other)
{
this(other.sequence);
}
public char charAt(int index)
{
return sequence[index];
}
// helper function to compare 2 objects of mystring. return negave number if
// this string is alphabetically before other,
// +ve number if this string ccomes after other and 0 if both are equal. if
// ignorecase is true comparison is case insensitive
private int compare(MyString other, boolean ignorecase)
{
char s1[], s2[];
int diff='a'-'A';
// store the shorter of the 2 sequences in s1. i.e s1 will be the
// shortest
// so that we need to compare only so many characters as the shorter one
if (sequence.length < other.sequence.length)
{
s1 = sequence;
s2 = other.sequence;
} else
{
s2 = sequence;
s1 = other.sequence;
}
// convert both to same case if ignorecase is true
if(ignorecase)
{
s1=toLowerCase(s1);
s2=toLowerCase(s2);
}
char ch1, ch2; // a single character from s1 and s2 respectively
int i;
for (i = 0; i < s1.length; i++)
{
ch1 = s1[i];
ch2 = s2[i];
if (ch1 != ch2)
return ch1 - ch2;
}
// at this point the previos return did not execute, which means all
// characters in s1 have matched. Now check if there were more characters in s2, if
// not then they matched exactly otherwise s1 is alphabetically before s2
if (i < s2.length) // if s2 was longer than s1 and s1 matched full its
// length
{
return -1; // s1 alphabetically before s2
}
else
return 0; // both matched
}
public int compareTo(MyString other)
{
return compare(other, false);
}
public int compareToIgnoreCase(MyString other)
{
return compare(other, true);
}
// appends str to ths string contents. a new object is returned
public MyString concat(MyString str)
{
char s[] = new char[sequence.length + str.sequence.length]; // new
// string
// will have
// length
// equal to
// sum of
// the 2
// sequences
// copy first sequence into the result
int i, j;
for (i = 0; i < sequence.length; i++)
s[i] = sequence[i];
// copy the sequence from other string,continue i from where it left off
for (j = 0; j < str.sequence.length; j++, i++)
s[i] = str.sequence[j];
return new MyString(s);
}
// returns true if this string ends with given suffix otherwise false
public boolean endsWith(MyString suffix)
{
// start comparing from end of the 2 sequences. If we reached the
// beginning of suffix sequence while comparing, then suffix is present
// in the end of this string
// get the last index for both sequences
int idx1 = sequence.length - 1, idx2 = suffix.sequence.length - 1;
if (idx2 > idx1) // we cant find a bigger suffix than the current
// sequence length . ex: "art".endsWith("star")
// should be false, since it is not possible to find
// star which is longer than art
return false;
while (idx2 >= 0) // makes sure suffix is bigger than the current
// sequence
{
if (sequence[idx1] != suffix.sequence[idx2]) // if not matching
// characters
return false;
idx1--; // go to previous index position
idx2--;
}
return true;
}
// returns true if this string is same as the other, returns false
// otherwise.
public boolean equals(MyString other)
{
return compareTo(other) == 0; // both strings are equal only if the
// compareto returns 0
}
// returns true if this string is same as the other ignoring case, returns
// false otherwise.
public boolean equalsIgnoreCase(MyString other)
{
return compareToIgnoreCase(other) == 0;// both strings (case
// insensitive) are equal only
// if the comparetoignorecase ()
// returns 0
}
// return first index of findme in ths string if found , -1 if not found
public int indexOf(char findMe)
{
return indexOf(findMe, 0);
}
// return first index of findme in ths string starting from fromIndex if
// found , -1 if not found
public int indexOf(char ch, int fromIndex)
{
for (int i = fromIndex; i < sequence.length; i++)
if (sequence[i] == ch)
return i;
return -1; /// not found until here so return -1
}
// return last index of ch in this string if found, returns -1 otherwise
public int lastIndexOf(char ch)
{
int last = -1; // assume ch is not found
for (int i = 0; i < sequence.length; i++)
{
if (sequence[i] == ch) // whenever ch is found, just save that index
// position.
last = i;
}
return last;
}
// returns length of this string
public int length()
{
return sequence.length;
}
// all ocuurences of search are replaced by replacement and new object
// returned
public MyString replace(char oldChar, char newChar)
{
MyString newstr = new MyString(this); // first make a copy of the this
// string into newstr
// now search for oldchar in the newstr sequence and replace it with
// newchar whenever found
for (int i = 0; i < newstr.sequence.length; i++)
{
if (newstr.sequence[i] == oldChar) // found a oldchar
newstr.sequence[i] = newChar; // replace with newchar
}
return newstr;
}
// returns true if this string begins with prefix, return false otherwise
public boolean startsWithString(MyString prefix)
{
// start comparing from beginning of the 2 sequences. If we reached the
// end of prefix then we return true
// we cant find a bigger prefix in a shorter sequence ex.
// "hello".startWithString("morning") can't be found since morning is
// longer than hello
if (prefix.sequence.length > sequence.length)
return false;
for (int i = 0; i < prefix.sequence.length; i++)
{
if (sequence[i] != prefix.sequence[i]) // if not matching characters
return false;
}
return true;
}
// return a substring starting from beginIndex . a new object is returned.
public MyString substring(int beginIndex)
{
// make sure the beginIndex is within valid range otherwise throwm
// exception
if (beginIndex < 0 && beginIndex > sequence.length)
throw new IndexOutOfBoundsException("Index out of bounds " + beginIndex);
// the substring will have only characters = sequence.len-beginindex
char s[] = new char[sequence.length - beginIndex];
// now start copying the characters starting from beginIndex till end of
// sequence
for (int i = beginIndex, j = 0; i < sequence.length; i++, j++)
{
s[j] = sequence[i];
}
return new MyString(s);
}
// returns substring starting from beginIndex to endIndex (excluded) . a new
// object is returned
public MyString substring(int beginIndex, int endIndex)
{
// make sure the beginIndex is within valid range otherwise throw
// exception
if (beginIndex < 0 || beginIndex > sequence.length)
throw new IndexOutOfBoundsException("Index out of bounds " + beginIndex);
// begin should not be larger than end
if (endIndex < 0 || endIndex > sequence.length || beginIndex > endIndex)
throw new IndexOutOfBoundsException("Index out of bounds " + endIndex);
char s[] = new char[endIndex - beginIndex]; // the substring will have
// only characters of length
// =endIndex-beginindex
// now copy characters startng from beginIndex till endIndex (excluded)
for (int i = beginIndex, j = 0; i < endIndex; i++, j++)
{
s[j] = sequence[i];
}
return new MyString(s);
}
private char[] toLowerCase(char seq[])
{
char s[]=new char[seq.length];
int diff='a'-'A'; //calculate the difference between ascii values for small a and capital A
char ch;
// now convert each character
for (int i = 0; i < seq.length; i++)
{
ch=seq[i];
if(ch>='A' && ch<='Z')
s[i] =(char) (ch+diff);
else
s[i]=ch;
}
return s;
}
// converts all character to lower case and a new object is returned
public MyString toLowerCase()
{
return new MyString(toLowerCase(sequence));
}
// converts all characters to upper case and new object is returned
public MyString toUpperCase()
{
return new MyString(toUpperCase(sequence));
}
private char[] toUpperCase(char seq[])
{
char s[]=new char[seq.length];
int diff='a'-'A'; //calculate the difference between ascii values for small a and capital A
char ch;
// now convert each character
for (int i = 0; i < seq.length; i++)
{
ch=seq[i];
if(ch>='a' && ch<='z')
s[i] =(char) (ch-diff);
else
s[i]=ch;
}
return s;
}
public String toString()
{
return original.toString();
}
// Extra credit methods
public MyString replaceAll(MyString search, MyString replacement)
{
MyString result = new MyString(this);
int start=0;
char s[]=result.sequence;
while (result.indexOf(search,start)>=0) // if search string is present
{
int len = result.sequence.length - search.sequence.length + replacement.sequence.length;
s= new char[len]; // new char sequence
int idx = result.indexOf(search,start), i, j; // find the index of search
// string
for (i = 0; i < idx; i++)// copy all character upto idx(excluded)
s[i] = result.sequence[i];
for (j = 0; j < replacement.sequence.length; i++, j++) // copy
// replacement
// string
s[i] = replacement.sequence[j];
start=i; //next we need to search from this location
for (j = idx + search.sequence.length; j < result.sequence.length; j++, i++)
{
// copy all characters from original string starting from idx +search length
s[i] = result.sequence[j];
}
result.sequence = s;// update results sequence
}
result=new MyString(s);
return result;
}
public int indexOf(MyString str)
{
return indexOf(str, 0);
}
public int indexOf(MyString search, int fromIndex)
{
if (fromIndex < 0 || fromIndex > sequence.length)
throw new IndexOutOfBoundsException("Index out of bounds " + fromIndex);
char s1[] = sequence, s2[] = search.sequence;
if (s2.length > s1.length) // can never find a long string in a shorter
// one
return -1;
int j,k;
//starting from the given index in s1, try to match all characters of s2 , if any didnot match
//go to next location of s1
for (int i = fromIndex; i < s1.length; i++)
{
for (j = 0,k=i; j < s2.length; j++,k++)
{
if (s1[k] != s2[j]) // any mismatch just stop comparison from
// there and continue from next postion
break;
}
if (j == s2.length) // j reached end of s2 , means all character
// matched starting from i
return i;
}
return -1; // not returned from function so far means not found, return
// -1
}
public boolean contains(MyString s)
{
return indexOf(s) >= 0; // if we can find that string using indexof i.e
// a non-negative index, then it is contained
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.