im doing a program where i need to return the index of MyString of the first occurence.
idk how to use the indexof in this situation. i think it might be something like
ch = indexof[] but im not sure. im still new at this and the api didnt help me much
/*********************************************************************************
This program will create classes that do similar operations to the Java String
Javier Perez
csc110
11/5/12
*********************************************************************************/
package string.assignment;
public class MyString
{
private char[] array;
private int size;
private int max;
public MyString()
{
array = new char[25];
max = 25;
}
public void setString(String newString)
{
if(newString.length() > 25)
{
System.out.println("/nEnter a number equal or less than 25 " );
}
else
{
for(int i=0; i < newString.length(); i++)
{
array[i] = newString.charAt(i);
}
}
}
public String toString()
{
return new String(array);
}
public char charAt(int index)
{
return array[index];
}
public boolean contains(char ch)
{
for(char c: array)
{
if(c == ch) return true;
}
return false;
}
public int indexOf( char ch )
{
ch = ch.indexOf();
}
return index;
}
For fetching the index of a certain character from your array, you would have to iterate over the array, and compare each character with the one you want to check. If any character matches, return the index immediately.
Also, your last return statement should be inside your method, else your code would not compile.
So, your
indexOfmethod in its simplest would be like this: –