Can someone please explain how to create this method public
Can someone please explain how to create this method!
public MyString replace(char oldChar, char newChar) // returns a new object of the class MyString where each occurrence of oldCHar is replaced by newChar. DO NOT modify the original object
Here is the rest of my code:
public class MyString {
public char [] charArray;
public MyString(String s){
charArray = new char[s.length()];
for(int i = 0; i < charArray.length; i++){
charArray[i] = s.charAt(i);
}
}
public MyString(char [] array){
charArray = array;
}
public int length(){
int length = charArray.length;
return length;
}
public boolean isEmpty(){
if(charArray.length == 0){
return true;
}
else{
return false;
}
}
// the tester keeps saying check, but Rachael said this was right
public MyString substring(int start, int end){
if(end > charArray.length || start < 0)
throw new ArrayIndexOutOfBoundsException();
char [] sub = new char [end - start];
for(int i = 0; i < sub.length; i++)
sub[i] = charArray[start + 1];
return new MyString(sub);
}
public char charAt(int position){
if(position > charArray.length || position < 0){
throw new ArrayIndexOutOfBoundsException();
}
return charArray[position];
}
public int indexOf(char character){
for(int i = 0; i < charArray.length; i++)
if(charArray[i] == character)
return i;
return -1;
}
public MyString replace(char oldChar, char newChar){
}
}
Solution
public MyString replace(char oldChar, char newChar){
for(int i=0,;i<oldChar.length,i++){// iterating the old char array
newChar[i]=oldChar[i];// replacing each occurrence of oldChar array with newChar array
}
MyString s=new MyString(newChar);// creating object of class MyString
return s;// returning the object of the class MyString
}

