How to search a sub string in string - java

I tried this code but this is not working for all strings.
import java.util.Scanner;
public class Substring {
public static void main(String[] args) {
String str;
String subStr;
int count=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the String : ");
str = in.nextLine();
System.out.println("Enter the Sub String : ");
subStr = in.nextLine();
for(int i =0 ; i <str.length(); i++)
{
if(str.charAt(i) == subStr.charAt(0))
{
for(int j=0 ; j<subStr.length();j++)
{
if( subStr.charAt(j) ==str.charAt(i+j))
count++;
else
{
count=0;
break;
}
}
}
}
if(count == subStr.length())
System.out.println("Sub String Matched !!");
else
System.out.println("String does not match !!");
}
}
What's wrong with this code ?

How to search a sub string in string
You don't need to loop over whole String. You can use string.indexOf(subString) to find the index of the substring in the string and it will return the index of the first occurrence of the substring. If you only want to ckeck whether String contains substring or not you can use string.contains(subString).

Try to decipher to the logic behind the code, so in plain english your code does the following:
LOGIC:
1)Enter a String via the Scanner and store it as str, do the same for the substring and store it as subStr.
2)Cycle through the each character of str via the for loop.
If the first character of the subStr is equal to any character with in str, then cycle through the characters of subStr. If the characters beyond this index are equal then increment the count variable each time the letters in each String are equal at the following indexes.
Else print String does not match.
3) If the number of similar characters in both Strings (denoted by the count variable) is equal to the length of the subString, then the subString is matched. Else no match.
ANSWER
So what went wrong?
I hope you notice on 2), The first bullet point you are only checking whether or not the first character of str is equal to the first character of subStr, if they are not equal you are then concluding that their is no match, which is false.
Consider the example:
str = "baloon"
subStr = "loon"
Your output would be: "String not matched"
This is because according to your code if 'b' != 'l' then theirs no match, which is false. That in essence is why your code does not work.
You could've just done the following:
if(str.contains(subStr)){
System.out.println("Sub-string matched");
}

Your code will only work if the substring is the end of the original string. This is because your code does not check that the entire substring was matched until it exits the first for loop. I moved the if (count == subStr.length() ) statement inside your first for loop and added a break if it finds the substring.
import java.util.Scanner;
public class Substring {
public static void main(String[] args) {
String str;
String subStr;
int count=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the String : ");
str = in.nextLine();
System.out.println("Enter the Sub String : ");
subStr = in.nextLine();
for(int i =0 ; i <str.length(); i++) {
if(str.charAt(i) == subStr.charAt(0)) {
for(int j=0 ; j<subStr.length();j++) {
if( subStr.charAt(j) ==str.charAt(i+j)) {
count++;
} else {
count=0;
break;
}
}
if(count == subStr.length()) {
System.out.println("Sub String Matched !!");
//int index = i;
break;
}
}
}
if(count == 0){
System.out.println("String does not match !!");
}
}
}
Note: If you then want the index at which the substring (first) occurred, you can set int index = i; before breaking the loop as shown in the commented line above.
Another note: don't tend to omit the {}s in if and else statements. While, technically, you don't need them for single statements, it can cause bugs if you need to edit code later...

Related

Finding substring in a given string by changing into char array

i am working on the following program. but its not giving me the correct output for string "nameiskhan" and substring as"name".
i know this might be a duplicate question but i couldn't find the desired answer in those questions.
import java.util.*;
import java.lang.String;
public class CheckingSubstring2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a String: ");
String string1 = input.next();
System.out.println("Please enter a second String: ");
String substring = input.next();
if (isSubstring(string1, substring)) {
System.out.println("The second string is a substring of the first.");
} else {
System.out.println("The second string is NOT a substring of the first.");
}
}
public static boolean isSubstring(String string1, String substring) {
char c[]=string1.toCharArray();
char d[]=substring.toCharArray();
boolean match = true;
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < d.length; j++) {
if (c[i] == d[j]) {
match = true;
} else {
match = false;
}
}
}
return match;
}
}
As you want to do it without contains, how about this?
What I do here is that going through the original string one pass and check if the substring can be found as consecutive characters in the main String.
public static boolean isSubstring(String string1, String substring) {
char c[]=string1.toCharArray();
char d[]=substring.toCharArray();
for (int i = 0; i < c.length; i++) {
if(c[i] == d[0]){
boolean match = false;
for(int j = 0; j < d.length; j++){
if(c[i+j] != d[j]){
match = false;
break;
} else{
match = true;
}
}
if(match) return true;
}
}
return false;
}
I would suggest becoming familiar with different debugging techniques. A very quick and easy one is a print statement. For example, you can print the values that you are comparing to make sure it looks reasonable. It will also give you an indication of how many times your loop is running. Stepping through the algorithm, the first two characters to be compared are c[0] = 'n' and d[0] = 'n'. That's good. The next two are c[0] = 'n' and d[1] = 'a'. That's not. Also, I assume you intend for the program to stop running if it finds a substring, but it doesn't appear that it would do so. Likewise, you might consider not comparing every element of the substring if a comparison has already been false.

Can't figure out what is wrong with my code

This is the instructions i got from my teacher:
Write your code in the file WordCount.java. Your code should go into a method with the following signature. You may write your own main method to test your code. The graders will ignore your main method:
public static int countWords(String original, int minLength){}
Your method should count the number of words in the sentence that meet or exceed minLength (in letters). For example, if the minimum length given is 4, your program should only count words that are at least 4 letters long.
Words will be separated by one or more spaces. Non-letter characters (spaces, punctuation, digits, etc.) may be present, but should not count towards the length of words.
Hint: write a method that counts the number of letters (and ignores punctuation) in a string that holds a single word without spaces. In your countWords method, break the input string up into words and send each one to your method.
This is my code:
public class WordCount {
public static void main(String[] args)
{
System.out.print("Enter string: ");
String input = IO.readString();
System.out.print("Enter minimum length for letter: ");
int length = IO.readInt();
IO.outputIntAnswer(countWords(input, length));
}
public static int countWords(String original, int minLegth)
{
int count = 0;
int letterCount = 0;
for(int i = 0; i < original.length(); i++)
{
char temp = original.charAt(i);
if(temp >= 'A' && temp <= 'Z' || temp >= 'a' && temp <= 'z')
{
letterCount++;
}
else if(temp == ' '|| i == original.length()-1)
{
if(letterCount >= minLegth)
{
count++;
}
letterCount = 0;
}
}
return count;
}
}
My college uses an autograder to grade project and i am keep getting one of the test case wrong. Can someone help me figure out what the problem is?
I figured the problem that your code is not able to compare the last character.It expects a space after the last character so that it can compare the last character since java doesn't use null character terminator for string termination.I have emulated the same code using Scanner class as I was having some trouble with io.So I have done the following change:
Scanner sc1,sc2;
sc1=new Scanner(System.in);
String input = sc1.nextLine()+" ";
I don't know if its possible to do:
String input = IO.readString()+" ";
but i think you should try appending blank space " " at the end of the string

String matching program

I am trying to make a java program to reverse the given string and each time iterate, compare with the reversed string then to print pass if matched else fail.
My program is:
package sss;
import java.util.Scanner;
public class ssi {
/**
* #param args
*/
public static void main(String[] args) {
String original,reverse="";
Scanner sc=new Scanner(System.in);
int ascii11,ascii12,ascii13,ascii14;
System.out.println("enter the string to be reversed");
original=sc.next();
int length=original.length();
for(int i=length-1;i>=0;i--)
{
reverse=reverse+original.charAt(i);
}
System.out.println(reverse);
//System.out.println(original);
for(int j=0;j<original.length()-1;j++)
{
ascii11=original.charAt(j);
ascii12=original.charAt(j+1);
ascii13=reverse.charAt(j);
ascii14=reverse.charAt(j+1);
if(Math.abs(ascii11-ascii12) == Math.abs(ascii13-ascii14))
{
System.out.println("pass");
}
else
{
System.out.println("fail");
}
}
// TODO Auto-generated method stub
sc.close();
}
}
here each time when the for loop iterates i am getting pass or fail for each pair of numbers but i want the o/p as to print only pass or fail ONCE.
can any one help me out please...
Example Code:
import java.util.Scanner;
public class PalindromeChecker {
public static void main(String[] args) {
String original;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the string to be reversed: ");
original = sc.next();
int halfLength = original.length()/2;
int lastIndex = original.length() - 1;
int i;
for(i = 0; i < halfLength; i++) {
if(original.charAt(i) != original.charAt(lastIndex - i)) {
System.out.println("Fail!");
break;
}
}
// Managed to match all characters
if(i == halfLength) {
System.out.println("Pass!");
}
sc.close();
}
}
Input/Output:
Enter the string to be reversed: banana
Fail!
Enter the string to be reversed: RADAR
Pass!
Enter the string to be reversed: asdwwdsa
Pass!
So the idea is to:
Compare the first half of the string with the second half of the string
Compare the first character with the last character
Compare the 2nd character with the 2nd last character, and so on.
If any character does not match, print Fail!
If the loop finishes, it implies that the string is a palindrome (original == reversed), print Pass!
You need to flag each comparison of the original and reversed characters with either a pass or a fail boolean value. Obviously if any of them are flagged with a fail, you can then terminate the algorithm and print fail. If the for loop continues with a pass right to the end, then print pass once outside of the for loop.
Your print statement is inside the loop , so its printing "pass" or "fail" for each loop. You should use a flag to check whether all the ascii characters are same. and then check the status of flag outside the loop.
OR
Use StringBuffer it has a built-in method to reverse string.
StringBuffer input = new StringBuffer("Your String to reverse");
String reverse = input.reverse().toString();
if(input.equals(reverse))
System.out.println("pass");
else
System.out.println("fail");
Move your if condition out of for loop.
for(int j=0;j<original.length()-1;j++)
{
ascii11=original.charAt(j);
ascii12=original.charAt(j+1);
ascii13=reverse.charAt(j);
ascii14=reverse.charAt(j+1);
}
if(Math.abs(ascii11-ascii12) == Math.abs(ascii13-ascii14))
{
System.out.println("pass");
}
else
{
System.out.println("fail");
}

Hangman in Java throws ArrayIndexOutOfBounds

My programs throws StringIndexOutOfBoundsException at this segment of code: temp1 = temp.replace('-', temp.charAt(p)); I'm trying to get the index of the same letter (after comparing inputted letter and word) and removing the '-' to show that the user has guessed correctly.** **I've been trying for hours to no avail. I think the problem lies in my loops. Thanks for the answers :) if I violated anything, please forgive me.
run:
-----
Enter a letter:
a
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range:
3
at java.lang.String.charAt(String.java:658)
at Hangman.main(Hangman.java:34)
Java Result: 1
import java.util.Scanner;
public class Hangman {
public static void main (String [] args){
Scanner sc = new Scanner(System.in);
String word = "Sample";
String temp = null;
String temp1 = null;
String letter = null;
int n;
int m=0;
int p = 0;
for (n = 0; n<word.length(); n++){
temp = word.replaceAll(word, "-"); //replaces the String word with "-" and prints
System.out.print(temp);
}
while (m<=5){ //the player can only guess incorrectly 5 times
System.out.println("\nEnter a letter:");
letter = sc.nextLine();
letter.toLowerCase();
if (word.contains(letter) == true){
p = word.indexOf(letter);
temp1 = temp.replace('-', temp.charAt(p)); //if the word contains the letter, "-" is replaced by the letter.
System.out.print(temp1);
}
else {
System.out.print("\nMissed: "+letter); //if not, Missed: +the given letter
m++; //to count for incorrect guesses
}
System.out.print(temp1);
}
System.out.println("Game Over.");
}
}
When you do this:
temp = word.replaceAll(word, "-");
...you are setting temp to be just "-", and not (for example) "----". To see why, consider if word is "hello"; then this line looks like:
temp = "hello".replaceAll("hello", "-");
So then later you are assuming that temp is as long as word is, because you find an index in word and try to access that character in temp. But temp is only one character long, hence the exception.
p = word.indexOf(letter);
temp1 = temp.replace('-', temp.charAt(p));
Try this one.....
This will solve your problem...!!
package beans;
import java.util.Scanner;
public class Hangman {
public static String replace(String str, int index, char replace){
if(str==null){
return str;
}else if(index<0 || index>=str.length()){
return str;
}
char[] chars = str.toCharArray();
chars[index] = replace;
return String.valueOf(chars);
}
public static void main (String [] args){
Scanner sc = new Scanner(System.in);
String word = "Sample";
String temp = "";
String letter = null;
int n;
int m=0;
int p = 0;
for (n = 0; n<word.length(); n++){
temp = temp + word.replaceAll(word, "-"); //replaces the String word with "-" and prints
}
System.out.print(temp);
while (m <= 5){ //the player can only guess incorrectly 5 times
System.out.println("\nEnter a letter:");
letter = sc.nextLine();
letter.toLowerCase();
if (word.contains(letter) == true){
p = word.indexOf(letter);
temp = replace(temp, p , word.charAt(p)); //if the word contains the letter, "-" is replaced by the letter.
System.out.println(temp);
}
else {
System.out.print("\nMissed: "+letter); //if not, Missed: +the given letter
m++; //to count for incorrect guesses
}
}
System.out.println("Game Over.");
}
}
You shoud check documentation for replaceAll() method.Cause you are using it wrong.
replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.
You putting whole string into regex parameter
If you do myString.replaceAll("\\.","-"); (use double backslash to specify regex) will replace any character beside newline with "-" check into regex. Regullar expressions
if (word.contains(letter) == true){
p = word.indexOf(letter);
temp1 = temp.replace('-', temp.charAt(p)); //if the word contains the letter, "-" is replaced by the letter.
System.out.print(temp1);
}
the word.indexOf(letter); return index of letter if that latter is present in string otherwise -1. that's why you are getting Exception.

What's wrong with my Java code? It should count the spaces, but returns 0

The code is copied below. It should return the number of spaces if the character variable l is equal to a space, but always returns a 0.
I've tested it with letters and it worked, for example if I'm asking it to increment when the variable l is equal to e and enter a sentence with e in, it will count it. But for some reason, not spaces.
import java.util.Scanner;
public class countspace {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = input.next();
System.out.println(wc(str));
}
public static int wc(String sentence) {
int c = 0;
for (int i = 0; i < sentence.length(); i++) {
char l = sentence.charAt(i);
if (l == ' ') {
c++;
}
}
return c;
}
}
Scanner.next() (with the default delimited) is only parsing as far as the first space - so str is only the first word of the sentence.
From the docs for Scanner:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
Use nextLine instead. You can also print the line for debugging:
System.out.println(str);
Use String str = input.nextLine(); instead of String str = input.next();
This is the way you should do to get the next string.
You could have checked that str has the wrong value.

Categories