Searching a String for a Character or a Substring

See also Quintessential Regular Expression Search Program.
String string = "madam, i am Adam"; // Characters // First occurrence of a c int index = string.indexOf('a'); // 1 // Last occurrence index = string.lastIndexOf('a'); // 14 // Not found index = string.lastIndexOf('z'); // -1 // Substrings // First occurrence index = string.indexOf("dam"); // 2 // Last occurrence index = string.lastIndexOf("dam"); // 13 // Not found index = string.lastIndexOf("z"); // -1

Comments

11 Jan 2010 - 10:38am by Morf3usz (not verified)

Great! Thanks for this advice, it was very useful for me!

20 Jan 2010 - 1:59am by Anonymous (not verified)

useful for starters

25 Jan 2010 - 3:12am by Anonymous (not verified)

Very good one for beginners

1 Feb 2010 - 1:05am by rast (not verified)

shouldn't index = string.indexOf("dam"); be 2?

1 Feb 2010 - 11:11pm by patrick

Yes, you're right. I just corrected it. Thanks.

23 Feb 2010 - 10:21am by Anonymous (not verified)

Very useful for beginners

10 Mar 2010 - 4:05pm by Dave (not verified)

Thanks so much for this!

13 Apr 2010 - 10:38pm by Armen (not verified)

How I can search all positions of "a"?

25 Apr 2010 - 8:43pm by Anonymous (not verified)

Hi, pls help me wit tis prog.. :(

1.Check Digits. Credit cards usually have a so-called check digit. This is a single digit that is assigned when the account number is developed and has a special property. One particularly simple mechanism is to assign the last digit of the sum of all the other digits. For example, suppose we have a nine-digit account number (including the check digit). The check digit would be the sum of the eight digits. This digit could be placed anywheres in the sequence, say the third digit. As a full example, suppose the eight numbers are 12345678. Their sum is 36; thus, 6 is the check digit. The account number is therefore 126345678.
Write a program to read in a nine digit integer from the keyboard and check it for
these rules. Write"okay" or "not okay" for the results of the test.

import java.lang.String;
class checkdig
{
public static void main(String args[])
{
int i,sum=0,x,a=0;
String s, y, s2, s1;
int[] arg = new int[9];
for(i=0;i<9;i++)
{
arg[i]=Integer.parseInt(args[i]);
}
for(i=0;i<9;i++)
{
sum=sum+arg[i];
a=a*10+arg[i];
}
s=""+a;
outer:
for(i=0;i<9;i++)
{
x=sum-arg[i];
x=x%10;
y=""+x;
s1=""+arg[i];
s2=s.replaceFirst(s1,"");
int index=s2.indexOf('y');
if(index!=-1)
{
System.out.println("Okay");
break outer;
}
s2=s;
}
System.out.println("Not Okay");
}
}

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.