PROCESSING A
STRING USING STRING OBJECT
AIM: To write a program in Java to get a name (string of characters) from the user and to find out the following:
- Length of the name
- Character ‘a’ is present or not in the name
- Location of ‘a’ present in the name
ALGORITHM:
- Declare an object of String named sName
- Declare variables of type int namely lCount, nIndex and fIndex for finding the length of the name, next index of ‘a’ and first index for searching the next occurance of ‘a’ in sName
- Get the name from the user and store it in sName using the object din of type DataInputStream
- Call the method length() of string object sName for finding the length and store it in lCount
- Call the method indexOf() of sName to find ‘a’ exists in it or not and store its result in nIndex
- Repeat the following until nIndex > 0 (i.e., next occurrence of ‘a’ exist)
- Print nIndex
- Set fIndex with the next value of nIndex (nIndex + 1)
- Call indexOf() on sName with the help of fIndex
PROGRAM:
import java.io.*;
public class StringObj
{
public static void
main(String[] args) throws IOException
{
String sName;
int lCount, nIndex=0,
fIndex;
DataInputStream din = new
DataInputStream(System.in);
System.out.print("Enter
a Name : ");
sName = din.readLine();
System.out.println("The
given Name is : " + sName);
lCount = sName.length();
System.out.println("The
length of the Name is : " + lCount);
nIndex =
sName.indexOf('a');
if (nIndex > 0)
{
System.out.println("The
letter a is Present in the Name");
System.out.println("The
letter appears in the following Indexes :");
while (nIndex > 0)
{
System.out.println(nIndex
+ " ");
fIndex = nIndex +
1;
nIndex =
sName.indexOf('a',fIndex);
}
}
}
}
Sample Run: