Ignore numbers in a string - java

Example:
String t;
String j ="j2se";
Scanner sc =new Scanner(System.in);
System.out.println("enter the search key:");
t=sc.next();
if (j.contains(t))
{
System.out.println("yes");
}
else System.out.println("no");
If the user enters 'j2', 'se' or 'j2s' as an input the output is 'yes'. If the input is 'jse' the output is 'no'.
Is there a method to ignore the number stored in string search like ignoring upper or lower case letters?

Why you don't juste create a copy of this string with no numeric inside ?
And after juste compare this new string with your array ?
Like :
String stringWithoutNumber = j.replaceAll("\\d+","");
stringWithoutNumber.contains(t);
Many of programs have a function called sanitize which clean the url or string before the comparaison.
Hope it's help
-- EDIT --
You don't need to put the + in \\d+ because the method replaceAll replace all the digit. But it's more efficient because it makes less replacement.

use replaceAll("\\d+","") on the String and then compare.
This removes all the numbers from your String. Now you could use this new String and compare.
or use :
\\W+ // replaces everything apart from characters .

Related

Looped If statements confusion - using scanners to find palindroms, cannot use .reverse for assignment

When I input any sentence, my output returns that any string is a palindrome, and I think that my replaceAll calls aren't working in some cases. This is likely due to error my part, because using the Scanner class in Java is new for me (more used to input from C++ and Python3). I added comments to make it clearer what my intentions were when writing the program.
import java.util.Scanner;
public class PalindromeTest
{
public static void main (String[] args)
{
Scanner stringScan = new Scanner(System.in); //Scanner for strings, avoids reading ints as strings
Scanner intScan = new Scanner(System.in); //Scanner for ints, avoids reading strings as ints
String forwardPal = ""; //Variables for the rest of the program
String reversePal = "";
String trimForward = "";
char tempChar;
int revCount;
int revPalLength;
int quit;
while (true) //Loop to keep the program running, problem is in here
{
System.out.println("Please enter a word or a sentence."); //Prompts user to enter a word or sentence, I assume that the program is counting
forwardPal = stringScan.nextLine();
trimForward = forwardPal.replaceAll(" " , ""); //Trims the forwardPal string of characters that are not letters
trimForward = trimForward.replaceAll("," , "");
trimForward = trimForward.replaceAll("." , "");
trimForward = trimForward.replaceAll("!", "");
trimForward = trimForward.replaceAll(":", "");
trimForward = trimForward.replaceAll(";", "");
revPalLength = trimForward.length() ; //Makes the reverse palindrome length equal to the length of the new trimmed string entered
for (revCount = revPalLength - 1; revCount >= 0; revCount--) //Loop to count the reverse palindrome and add each character to the string reversePal iteratively
{
tempChar = trimForward.charAt(revCount);
reversePal += tempChar;
System.out.println(reversePal);
}
if (trimForward.equalsIgnoreCase(reversePal)) //Makes sure that the palindrome forward is the same as the palindrome backwards
{
System.out.println("Congrats, you have a palindrome"); //Output if the sentence is a palindrome
}
else
{
System.out.println("Sorry, that's not a palindrome"); //Output if the sentence isn't a palindrome
}
System.out.println("Press -1 to quit, any other number to enter another sentence."); //Loops to ask if the user wants to continue
quit = intScan.nextInt(); //Checks if the user input a number
if (quit == -1) //If the user inputs -1, quit the program and close the strings
{
stringScan.close();
intScan.close();
break;
}
}
}
}
Your problem is this line
trimForward = trimForward.replaceAll("." , "");
That function takes the first argument as a regex, and the dot means that it is replacing all characters as a "".
Instead, use
trimForward = trimForward.replace("." , "");
In fact, all your lines should be using #replace instead of #replaceAll as none of them take advantage of regex. Only use those if you plan to take advantage of it.
Or in fact, if you do want to use a regex, this is a nice one which does all of that in one neat line.
trimForward = forwardPal.replaceAll("[ .!;:]" , "");
I hope this was of some help.
The simplest fix is to use replace() instead of replaceAll().
replace() replaces all occurences of the given plain text.
replaceAll() replaces all occurences of the given regex.
Since some of your replacements have special meaning in regex (specifically the dot ., which means any character), you cant use replaceAll() as you are currently (you'd have to escape the dot).
It's common, and quite reasonable, to assume that replace() replaces one occurrence and replaceAll() replaces all occurrences. They are poorly named methods, because they interpret their parameters differently, yet both replace all matches.
As an aside, you may find this briefer solution of interest:
forwardPal = forwardPal.replaceAll("\\W", ""); // remove non-word chars
boolean isPalindrome = new StringBuilder(forwardPal).reverse().toString().equals(forwardPal);

How to check a string which only contains one word. If a string has a sentence it should return false

I know it's a wierd to ask a question like this. But i've got no options. The problem is
I've come across a requirement where i happens to add a condition where, If there is an input as a string, I should be able to allow all the strings which only contains one word. So if there are many words I should reject.
How to add such check when I don't have specificity on such string.
If the words are separated by some kind of white space, you could use a simple regular expression for this:
Pattern wordPattern = Pattern.compile("\\w+");
Matcher wordMatcher = wordPattern.matcher(inputString);
if (!wordMatcher.matches()) {
// discard user input
}
This will match all word characters ([a-zA-Z_0-9]). If your definition of "word" is different, the regex will need to be adapted.
So many ways you can achieve it,
One of the simplest is..
String str = "abc def";
String [] array = str.trim().split(" ");
if(array.lenght==1){
// allow if lenght = 1, or a word....
}else{
// don't allow if lenght !=1 , or not a word..., dosomething else, or skip
}
You can split the string on a regular expression that represents a sequence of white spaces and then see how many parts you get. Here's a function to do it:
public static boolean is_word(String s) {
return (s.length() > 0 && s.split("\\s+").length == 1);
}
System.out.println(is_word("word"));
System.out.println(is_word("two words"));
System.out.println(is_word("word\tabc\txyz"));
System.out.println(is_word(""));
Output:
true
false
false
false
The length check on the input string is required if you want to say that an empty string is not a word, which would seem reasonable.

.replace to replace input letters with symbols

I want to make everything the user enters capitalized and certain letters to be replaced with numbers or symbols. Im trying to utilize .replace but something is not going right. Im not sure what im doing wrong?
public class Qbert
{
public static void main(String[] args)
{
//variables
String str;
//get input
Scanner kb = new Scanner(System.in);
System.out.print(" Please Enter a Word:");
//accept input
str = kb.nextLine();
System.out.print("" );
System.out.println(str.toUpperCase()//make all letters entered uppercase
//sort specific letters to make them corresponding number, letter, or symbol
+ str.replace("A,#")+ str.replaceChar("E","3")+ str.replaceChar ("G","6")
+ str.replaceChar("I","!")+ str.replaceChar("S","$")+ str.replaceChar ("T","7"));
}
}
In Java, Strings are immutable. This means that modifying a string will result in a new string. E.g.
str.replace("a", "b");
this will replace all the occurrences of 'a' to 'b' in a new string. Original string will remain unaffected. So, to apply the formatting on the actual string, we will have to write:
str = str.replace("a", "b");
Similarly, if we want to do multiple replacements then, we need to append replace calls together, e.g.
str = str.replace("a","b").replace("c", "d");
Going by this, if you want to perform the substitution, the last system.out in your code will be:
System.out.println(str.toUpperCase().replace("A","#").replace("E","3")
.replace("G","6").replace("I","!").replace("S","$").replace("T","7"));
String doesn't have a replaceChar method. You probably wanted to use method replace.
And String.replace() takes 2 arguments:
public String replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target
sequence with the specified literal replacement sequence. The
replacement proceeds from the beginning of the string to the end, for
example, replacing "aa" with "b" in the string "aaa" will result in
"ba" rather than "ab".
You have written str.replace("A,#")+... instead of str.replace("A","#")+..., and so on
One more thing - use a good IDE like Eclipse or Intellij IDEA, they will highlight the parts of your code where you have errors.
public static void main(String... args) {
// variables
String str;
// get input
Scanner kb = new Scanner(System.in);
System.out.print(" Please Enter a Word:");
// accept input
str = kb.nextLine();
System.out.print("");
System.out.println(str.toUpperCase()); // Upper Case
System.out.println(str.toUpperCase().replace("A", "#").replace("E", "3")
.replace("E", "3").replace("G", "6").replace("I", "!").replace("S", "$").replace("T", "7") );
}
This should work like you want it to. Hope you find this helpful.
As you want to make multiple changes to the same string, you just use
str.toUpperCase().replace().replace().... This means you are giving
the output of str.toUpperCase() to the first replace function and so
on...
System.out.println(str.toUpperCase()
.replace("A","#")
.replace("E","3")
.replace("G","6")
.replace("I","!")
.replace("S","$")
.replace("T","7"));

Deliminter is not working for scanner

The user will enter a=(number here). I then want it to cut off the a= and retain the number. It works when I use s.next() but of course it makes me enter it two times which I don't want. With s.nextLine() I enter it once and the delimiter does not work. Why is this?
Scanner s = new Scanner(System.in);
s.useDelimiter("a=");
String n = s.nextLine();
System.out.println(n);
Because nextLine() doesn't care about delimiters. The delimiters only affect Scanner when you tell it to return tokens. nextLine() just returns whatever is left on the current line without caring about tokens.
A delimiter is not the way to go here; the purpose of delimiters is to tell the Scanner what can come between tokens, but you're trying to use it for a purpose it wasn't intended for. Instead:
String n = s.nextLine().replaceFirst("^a=","");
This inputs a line, then strips off a= if it appears at the beginning of the string (i.e. it replaces it with the empty string ""). replaceFirst takes a regular expression, and ^ means that it only matches if the a= is at the beginning of the string. This won't check to make sure the user actually entered a=; if you want to check this, your code will need to be a bit more complex, but the key thing here is that you want to use s.nextLine() to return a String, and then do whatever checking and manipulation you need on that String.
Try with StringTokenizer if Scanner#useDelimiter() is not suitable for your case.
Scanner s = new Scanner(System.in);
String n = s.nextLine();
StringTokenizer tokenizer = new StringTokenizer(n, "a=");
while (tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}
or try with String#split() method
for (String str : n.split("a=")) {
System.out.println(str);
}
input:
a=123a=546a=78a=9
output:
123
546
78
9

Searching for an int inside a string user input

I am currently doing an assignment for class and I would like to know how to find an integer inside a string input. So far in the code I have created a way to exit the loop. Please don't give me code just give me some ideas. Keep in mind that I am quite new to java so please bear with me. Thanks.
EDIT: I forgot to mention that the string input should be like "woah123" and it should find only the "123" portion. Sorry
import java.util.Scanner;
public class DoubleTheInt
{
public static void main(String[] args)
{
int EXIT = 0;
while(EXIT == 0)
{
Scanner kbReader = new Scanner(System.in);
System.out.println("What is your sentence?");
String sentence = kbReader.next();
if(sentence.equalsIgnoreCase("exit"))
{
break;
}
}
}
}
For learning purpose what you can do is traverse the whole string and check only for the digits. In this case you will also learn how to check char-by-char in a string if in future you may require this also you will get the digits of that string. Hope that solves your problem.
Here's what you do...
Replace all non numeric characters with empty string using \\D and String.replaceAll function
Parse your string (after replacing) as integer using Integer.parseInt()
Edited after Christian's comment :
replaceAll() function replaces occurances of particular String (Regex is first argument) with that of the second argument String..
\\D is used to select everything except the numbers in the String. So, the above 2 lines combined will give "1234" if your String is "asas1234" .
Now , Integer.parseInt is used to convert a String to integer.. It takes a String as argument and returns an Integer.
Since you are not asking for code , I am giving you some suggestions.
Use regex in string method to find the numbers and to remove all the
non numbers.
Parse the string to integer.
Unless your assignment "is" a regex assignment, I suggest you do it the non-regex way. i.e, by reading character by character and checking for integers or reading the string and converting to a char array and process.
I'm not sure what your teacher intends you to do, but there are two ways-
Read character by character and filter the numbers by their ASCII code. Use BuffferedReader to read from standard input. And use read() method. Figure out the ASCII code range for numbers by experimenting.
Read the entire String at once(using either Scanner or BufferedReader) and see what you can do from the String API(as in the methods available for String).
Use Regular Expression : \d+
String value = "abc123";
Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher(value);
int i = Integer.valueOf(m.group(1));
System.out.println(i);
output
123

Categories