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
Great! Thanks for this advice, it was very useful for me!
useful for starters
Very good one for beginners
shouldn't index = string.indexOf("dam"); be 2?
Yes, you're right. I just corrected it. Thanks.
Very useful for beginners
Thanks so much for this!
How I can search all positions of "a"?
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");
}
}