How to compare 2 strings if they have spaces? - java

I'm having some problem with a simple program I'm working on, I just need to ask the user if he wants the regular price or the sale price. And he needs to respond in a string value. Now I know that I just have to use if(price.equals("sale") == true). But the problem comes if I want the user to type something that has spaces in the words, example: if(price.equals("regular price") == true) when I the user types in "regular price" I don't get a response I wanted.
I'm also learning Java by the way.

You can determine if a string contains a word like this:
if (price.toLowerCase().contains("regular"))
If you want to get fancy, you can use regex to match a whole word (eg not "irregular"):
if (price.matches("(?i).*\\bregular\\b.*"))

java equals() method/function works perfectly with the spaces too. Also you don't need to compare the result with true/false. If two string is equal then equals() will automatically return true else it will return false.
public class MyClass {
public static void main(String args[]) {
String a = "A B C";
if(a.equals("A B C")){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
I tested the following program and it returned true while the string has spaces in it.

You want to compare strings with spaces right?
Then you can first compare their lengths, then
If string contains space split it by it, again compare lengths, next check every string.
If it not contains space, just use equals once, here what i come up with:
class cmp {
public static void main(String[] args) {
String s = "test some";
String s2 = "test some";
String s3 = "test not";
String s4 = "testxsome";
System.out.println(cmpStr(s,s2)); // True
System.out.println(cmpStr(s,s3)); // False
System.out.println(cmpStr(s,s4)); // False
}
public static boolean cmpStr(String str1, String str2) {
if (str1.length() != str2.length()) {
System.out.println("Length mismatch.");
return false;
}
if (str1.contains(" ") || str2.contains(" ")) {
String[] a1 = str1.split(" ");
String[] a2 = str2.split(" ");
if (a1.length != a2.length) {
System.out.println("Split Length mismatch.");
return false;
}
for (int i = 0; i < a1.length; i++) {
if (!a1[i].equals(a2[i])) {
System.out.println("One of split mismatch." + a1[i] + " " + a2[i] );
return false;
}
}
} else {
if (!str1.equals(str2)) {
System.out.println("Regular equals returns false.");
return false;
}
}
return true;
}
}

Here I see three methods
Remove all the spaces and hidden characters from the string and check
String input = "regular price";
input = input.replaceAll("\\s+","");
if(price.equals(input))
{
//your code here
}
Check whether the word contains keywords
if (price.toLowerCase().contains("regular"))
Create a regular expression to match your words

Related

how i can use this form 000-00-000 to input

the question
write a program that reads in a line consisting of a student's name, social security number, user ID, and password(separat by one space). The program outputs the string in which all digits of the social security number, and all the characters in the password are replaced by x.( The social security number is in the form 000-00-000, and the user ID and password do not contain any spaces,and the name does not contain any digits.)
for example
input :the user input : jimin 222-11-222 jimin22 jim2000
explanation: jimin is the name of user -should not contain any digits-
222-11-22 is social security number in form "000-00-000"
jimin22 is the user id
jim2000 is the user password
the output shoud be like
output: jimin xxx-xx-xxx jimin22 xxxxxxx
i dont know how the name making it without digits
and i dont know how output the social security number in form "000-00-000"
Scanner input=new Scanner(System.in);
String name,So_n,ue_id,password;
int x;
////to input
name=input.next();
So_n=input.next();
ue_id=input.next();
password=input.next();
///to output
System.out.print(name+"\t");
x = So_n.length();
for(int i=0;i<x;i++){
System.out.print("x"); }
System.out.print("\t");
System.out.print(ue_id+"\t");
x = password.length();
for(int i=0;i<x;i++){
System.out.print("x"); }
It seems that crux of the issue is to replace characters rather than just printing out some 'X' ones. Therefore, an approach that handles replacement would be most appropriate.
Here are a couple of sample methods that could address the OP's question. Additional methods to validate the user name, the password in terms of whatever complexity, etc., can be easily added. No details were provided on what to do in the event of an invalid input, so the one case here merely puts out a message.
// for a non-null password, return a String of the same length with all
// of the characters set to an 'X'
public static String getObfuscatedPassword(String pw)
{
Objects.requireNonNull(pw, "Null pw input");
return pw.replaceAll(".", "X");
}
// for a non-null ssn, return a String where every digit is replaced
// by an 'X'; other characters (such as a -) are unchanged
public static String getObfuscatedSSN(String ssn)
{
Objects.requireNonNull(ssn, "Null ssn input");
return ssn.replaceAll("[0-9]", "X");
}
// return true if the specified ssn is not null and
// matches the format of ###-##-###
public static boolean isValidSSN(String ssn)
{
// ensures there is something for us to validate
// NOTE: technically the .isEmpty is not needed
if (ssn == null || ssn.isEmpty()) {
return false;
}
// ensure in the format of ###-##-###
return Pattern.matches("[\\d]{3}-[\\d]{2}-[\\d]{3}", ssn);
}
// returns true if the username has at least one character, and
// no digits; does not prevent having spaces in the name (could
// be added); uses a for loop rather than regular expressions for
// a fun difference in approach
public static boolean isValidUsername(String name)
{
boolean charFound = false;
boolean digitFound = false;
if (name == null || name.isEmpty()) {
return false;
}
for (int i = 0; i < name.length(); ++i) {
// check if the current name[i] is a letter or digit
// the OR will keep a true once it is set
charFound = charFound || Character.isLetter(name.charAt(i));
digitFound = digitFound || Character.isDigit(name.charAt(i));
}
return charFound && ! digitFound;
}
Driver example:
public static void main (String[] args) throws java.lang.Exception
{
String user = "jimin";
String ssn = "222-11-222";
String password = "WhatAWonderfulWorldItWouldBe";
if (! isValidSSN(ssn)) {
System.err.println("Invalid SSN");
}
String xdSsn = getObfuscatedSSN(ssn);
String xdPw = getObfuscatedPassword(password);
System.out.printf("%12s\t%s\t%s%n", user, xdSsn, xdPw);
}
Sample Output:
jimin XXX-XX-XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX
Using better variable names would be a good thing.
Some online example at: https://ideone.com/cPV2ob
To replace the digits in the SSO:
x = So_n.length();
for (int i = 0; i < x; i++) {
if ('0' <= So_n.charAt(i) && So_n.charAt(i) <= '9') {
System.out.print("x");
} else {
System.out.print(So_n.charAt(i));
}
}

Trying to figure out how to print a certain string, if the string contains a certain first character

Trying now to figure out how to add multiple searches to name.startsWith.
So that i can find out of the elements added search for a, e, i, o and u. Instead of just "a".
"Create a method called printFizzBuzz(). This method should loop through the collection, and print out the elements (each String on one line). If the String starts with a, e, i, o or u, instead of printing the String, it should print "Fizz" on the line. If the String starts with A, E, I, O or U, instead of printing the String, it should print "Buzz". For example, if the collection contained the names "banana", "Apple", "orange", "pear", "peach", "kiwi fruit", "Grape", then the printout would look like: Fizz Buzz Fizz pear peach kiwi fruit"
public class SchoolNames
{
private ArrayList<String> names;
/**
* Creates a collection of names.
*/
public SchoolNames()
{
names = new ArrayList<>();
}
/**
* Add a name to the collection.
*/
public void addName(String Name)
{
names.add(Name);
}
/**
* Remove a name from the collection.
*/
public void removeName(int index)
{
if (index >= 0 && index < names.size())
{
names.remove(index);
System.out.println("Name removed");
}
else
{
System.out.println("No names to remove");
}
}
/**
* Return the number of names stored in the collection.
*/
public int getNumberOfNames()
{
return names.size();
}
public void listAllNames()
{
for (String name : names)
{
if (name.startsWith("a"))
{
System.out.println("Fizz");
}
else if (name.startsWith("A"))
{
System.out.println("Buzz");
}
else
{
System.out.println(name);
}
}
}
}
You should add an else statement for that. If the all condition fail in the if and else if then only else part will be executed, Otherwise not
if (name.contains("a")) {
System.out.println("Fizz");
} else if (name.contains("A")) {
System.out.println("Buzz");
} else {
System.out.println(name);
}
Update:
If the reqiurement to check the start element of a string then you should check with name.startsWith("a")
Update:
Question:
YES! that worked brilliantly! The last thing i need to figure out, is how to add multiple characters to the name.startsWith. I've tried adding "a", "e". but it does not work
No. it shouldn't startsWith accept a single string paramater. You can check this with the or operator.
if (name.startsWith("a") || name.startsWith("e")//....rest of check)
You may try with the following snippets below,
String str ="Anglo"; //sample input
String vowelinCaps = "AEIOU";
String vowelinSmall = "aeiou";
if (vowelinCaps.indexOf(str.charAt(0)) >= 0)
System.out.println("Fizz");
else if (vowelinSmall.indexOf(str.charAt(0)) >= 0)
System.out.println("Buzz");
else
System.out.println(str);
Update-
char java.lang.String.charAt(int index) returns the char value at the specified index.
int java.lang.String.indexOf(int ch) returns the index of the first occurrence of the character in the character sequence represented by
this object, or -1 if the character does not occur.
As stated in the other answer, an else statement is indeed missing.
You also probably want to avoid having an if statement per letter (a,e,i....), so you might do something like :
for (String name : names)
{
char firstChar = name.charAt(0);
if ("aeiou".indexOf(firstChar)>-1)
{
System.out.println("Fizz");
}
else if ("AEIOU".indexOf(firstChar)>-1)
{
System.out.println("Buzz");
}
else
{
System.out.println(name);
}
}
You can use following regex code to replace word based on your pattern
public void findAndReplace(List<String> items) {
StringBuffer stringBuffer = new StringBuffer();
for(String eachItem : items) {
if(isMatchFound(eachItem,"^[AEIOU]")) {
stringBuffer.append("Buzz");
stringBuffer.append(" ");
}else if(isMatchFound(eachItem,"^[aeiou]")) {
stringBuffer.append("Fizz");
stringBuffer.append(" ");
}else {
stringBuffer.append(eachItem);
stringBuffer.append(" ");
}
}
System.out.println(stringBuffer);
}
public Boolean isMatchFound(String item,String pattern) {
return item.matches(pattern);
}
Regex : ^[AEIOU] check string's first(^) charactor in [AEIOU] data set or not.
You might also be able to try
`String lowercase = "aeiou";
String upercase = "AEIOU";
String text = "apple";
if(lowercase.contains(text.charAt(0))){
System.out.println("fuzz");
}else if(upercase.contains(text.charAt(0)))){
System.out.println("buzz");
}else{
System.out.println(text)
}`
you might have to use String.valueOf(text.charAt(0)), to have it as a string
Do you mean to do it this way?:
public class StringTest {
public static void main(String args[]){
String testString = "aatest";
if (testString.matches("(aa|bb|cc|dd|dd).*")){
System.out.println("true");
}
if(testString.startsWith("aa") || testString.startsWith("bb")){ // other conditions as well
System.out.println("true");
}
}
}

Print a corresponding string of numbers of relationship between two DNA string in Java

I have the following two DNA strings "AACAGTTACC" and "TA-AGGT-CA", I would like to print a corresponding string of numbers, where two elements of two strings indicate a match (0), two elements indicate a mismatch (1) and one element indicates a gap (2).
For example the above two string would produce “10220010201”
I tried a loop through one of the string and check if string.charAt(i).contains("-") but it does not work.
String numbers = "";
for(int k = 0; k<adnX.length();k++) {
// I would like to append numbers to the numbers string
StdOut.printf("%s %s\n", adnX.charAt(k),adnY.charAt(k));
}
Two methods are presented here:
the main method and an auxiliary method.
The auxiliary checks if a given character is a valid DNA character.
The main method has two main parts.
Firstly, it initialises s1 and s2 with the required DNA strings and creates s3 which is an empty string. s3 will be used to store the corresponding numbers in case of a match, miss-match or gap. It assumes that both s1 and s2 have the same length.
In the first part it checks if the character at i-th position in s1 and s2 is a valid DNA character, if it's not it appends a 2 to s3.
In the second part (i.e., of the if statement, the else), it checks if the character at i-th position in s1 is the same as character at i-th position in s2. If it is then it appends a 0, otherwise it appends a 1.
The result is printed at the end.
public class DNACheck {
public static boolean isDNA(char c) {
String dna = "ATGC";
boolean inSequence = false;
for (int i = 0; i < dna.length() && !inSequence;i++) {
if (dna.charAt(i) == c) inSequence = true;
}
return inSequence;
}
public static void main(String[] args) {
String s1 = "AACAGTTACC";
String s2 = "TA-AGGT-CA";
String s3 = "";
for(int k = 0;k< s1.length();k++) {
// I would like to append numbers to the numbers string
if (!isDNA(s1.charAt(k)) || !isDNA(s2.charAt(k))) {
s3 = s3 + '2';
}
else {
if (s1.charAt(k) == s2.charAt(k)) {
s3 = s3 + '0';
}
else {
s3 = s3 + '1';
}
}
}
System.out.println(s3);
}
}
Assuming that inputs always have the same length and two gaps should result in a match:
String adnX = "AACAGTTACC";
String adnY = "TA-AGGT-CA";
StringBuilder numbers = new StringBuilder();
for (int i = 0; i < adnX.length(); i++) {
if (adnX.charAt(i) == adnY.charAt(i)) {
numbers.append(0);
} else if (adnX.charAt(i) == '-' || adnY.charAt(i) == '-') {
numbers.append(2);
} else {
numbers.append(1);
}
}
System.out.println(adnX);
System.out.println(adnY);
System.out.println(numbers);
Will output:
AACAGTTACC
TA-AGGT-CA
1020010201

How to print out found words from a trie in java?

I have a method here that searches and prints what i think is all letter combinations of a dictionary in trie form the node entered.
I want to specify each print out and and it to my search(string x) method that finds if a word is in the dictionary.
I can't work out how to specify each letter combination as a string. I am printing them out on a line but don't know how to make that line of print a string to pass into the search method.
public void print(Node node) {
if(node == null) return;
for(int i = 0; i < R; i++) {
if(node.next[i] != null) {
//printing each character
System.out.print((char) (97 + i));
//identifying letter combo
if(node.next[i].isWord == true) {
//here i want to make that combo a string
System.out.println();
}
print(node.next[i]);
}
}
}
You can use
String s1 = "";
s1 = s1 + (char)(97+i); to append characters to a string. You can pass this to your search function
Something, this way,
Initialise the string to "" outside the for loop String s1 = ""
While looping keep adding the characters to the String to maintain a string
s1 = s1 + (char)(97+i);
Now,
if(node.next[i].isWord == true)
{
//u can use the String here;
System.out.println(s1);
}

Java, Check if a String is a palindrome. Case insensitive

I want to write a java method to return true if a string is a palindrome.
Here is what I have so far:
String palindrome = "...";
boolean isPalindrome = palindrome.equals(
new StringBuilder(palindrome).reverse().toString());
My problem with this is that it does not consider a word like: Race car to be a palindrome.
Doc, note, I dissent. A fast never prevents a fatness. I diet on cod.
What is the best way to test if this is a palindrome, with case insensitivity and ignoring punctuation.
Use this regex to remove all punctuation and spaces and convert it to lower case
String palindrome = "..." // from elsewhere
boolean isPalindrome = palindrome.replaceAll("[^A-Za-z]", "").toLowerCase().equals(new StringBuilder(palindrome.replaceAll("[^A-Za-z]", "").toLowerCase()).reverse().toString());
Try this ..
public static void main(String[] args) {
boolean notPalindrome = false;
String string = "Doc, note, I dissent. A fast never prevents a fatness. I diet on cod";
string = string.replaceAll("[^a-zA-Z]+","").toLowerCase();
char[] array = string.toCharArray();
for(int i=0, j=array.length-1; i<j; i++, j--) {
if(array[i] != array[j]) {
notPalindrome = true;
break;
}
}
System.out.println(string + " is palindrome? " + !notPalindrome);
}
Use the below regex, to keep even numeric characters in the Palindrome, if needed. Else, you can just remove the 0-9 from the regex.
String palindrome = "..." // from elsewhere
String regex = "[^A-Za-z0-9]";
boolean isPalindrome = palindrome.equals(new StringBuilder(palindrome.replaceAll(regex, "").toLowerCase()).reverse().toString());
Here is a non regex solution.
public class so4
{
public static void main(String args[])
{
String str = "Doc, note, I dissent. A fast never prevents a fatness. I diet on cod";
char c[] =str.toCharArray();
String newStr="";
for(int i=0;i<c.length;i++)
{
if( (c[i]>=65 && c[i]<=90) || (c[i]>=97 && c[i]<=122)) //check ASCII values (A-Z 65-90) and (a-z 97-122)
{
newStr = newStr + c[i];
}
}
boolean isPalindrome = newStr.toLowerCase().equals(new StringBuilder(newStr.toLowerCase()).reverse().toString());
System.out.println(isPalindrome);
}
}
convert to lower case
use a regex to remove everything but letters
reverse the string using a StringBuilder
compare the strings for equality
Code:
/**
* Returns true if s is a palindrome, ignoring whitespace
* punctuation, and capitalization. Returns false otherwise.
*/
public boolean isPalindrome(String s) {
String forward = s.toLowerCase().replaceAll("[^a-z]", "");
String reverse = new StringBuilder(forward).reverse().toString();
return forward.equals(reverse);
}
For more info, see the documentation for String and StringBuilder:
String.toLowerCase()
String.replaceAll()
StringBuilder.reverse()
You can also find it by googling "Java 7 String" and clicking the first result.

Categories

Resources