user3596476
user3596476

Reputation: 1

How to determin if a string can generate another string

I am using contains to see if String (A) can generate String(B) (both taken from the user)

package trabajogrupal;

import java.util.Scanner;

public class TrabajoGrupal {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        char resp1 = 's';
        String resp2 = "";
        while (resp1 == 's') {
            System.out.println("Ingrese la primer cadena ");
            String cadena = in.nextLine().toLowerCase();
            System.out.println("Ingrese la segunda cadena ");
            String cadena1 = in.nextLine().toLowerCase();
            if (cadena.contains(cadena1)) {
                System.out.println("La cadena " + cadena + " puede generar la cadena " + cadena1);
            } else {
                System.out.println("La cadena " + cadena + " no puede generar la cadena " + cadena1);
            }
            System.out.println("Desea continuar ");
            resp2 = in.nextLine();
            resp2 = resp2.toLowerCase();
            resp1 = resp2.charAt(0);
        }
    }
}

the first string should contain the second string but what happens is that it keeps getting in the else statement. Why?

Upvotes: 0

Views: 79

Answers (4)

ColonelMo
ColonelMo

Reputation: 134

you can use

if(cadena.indexOf(cadena1) >= 0){
    //todo
}

Upvotes: 0

Andrei
Andrei

Reputation: 3106

You could check if you can make String B with String A's characters than you could do it like this:

System.out.println("First string");
String firstInput = geek.nextLine().toLowerCase();
System.out.println("Second string");
String secondInput = geek.nextLine().toLowerCase();
char[] secondInputCharacters = secondInput.toCharArray();
boolean contains = true;
for(int i = 0; i < secondInputCharacters.length; ++i)
{
    if(firstInput.indexOf(secondInputCharacters[i]) < 0)
        contains = false;
}

What this does is:

  • read the 2 strings and transform them to lowercase
  • take the characters of the second string
  • iterate over those characters
  • for each character, if it doesn't exist in the first string, than it should return false

Upvotes: 0

Daksh Shah
Daksh Shah

Reputation: 3113

You may try flushing the input before taking it, so that if there are extra characters like newline, (\n) they are ignored

Upvotes: 0

Jakkra
Jakkra

Reputation: 651

Step though all characters in string B and check if the character is in string A.

Do this by using A.indexOf(each character in B). As long as it don't return - 1 the character is in string A.

Upvotes: 1

Related Questions