Method to check if a Char is present on a specific String - java

I need to write a program where the main reads two strings as input: if the strings have the same length, then it has to pass the whole first string and the first char of the second string to a method called find, which has to return 'true' if the character appears even a single time on the string. If the length differs, then it will pass the whole second sentence and the last char of the first string to find. At last, the main will give whatever the method returns as output, so it has to be true, or false. I've created the whole main, and it works correctly, but I have no idea how to create the find method. Here is the code:
import java.util.Scanner;
public class Exercise {
/*
* public static boolean find(String... sentence, char... character) {
* // No, I can't use multiple varargs...
* }
*/
public static void main(String[] args) {
String first, second;
char firstChar, lastChar;
Scanner keyboard = new Scanner(System.in);
int lengthFirst, lengthSecond;
boolean goal = true;
first = keyboard.nextLine();
lengthFirst = first.length();
lastChar = first.charAt(lengthFirst - 1);
second = keyboard.nextLine();
lengthSecond = second.length();
firstChar = second.charAt(0);
System.out.println("Length 1: " + lengthFirst); // Those lines are test lines.
System.out.println("Length 2: " + lengthSecond); // They're here just to check
System.out.println("Char 1: " + firstChar); // if everything else works.
System.out.println("Char 2: " + lastChar);
if (lengthFirst == lengthSecond) {
goal = find(first, firstChar);
System.out.println("Goal is: " + goal);
System.exit(0);
} else
goal = find(second, lastChar);
System.out.println("Goal is: " + goal);
System.exit(0);
}
}
I was thinking about using the varargs option, using a varargs for the String, and another for the char, and then using a 'for' loop inside of the method to check if the character appears or not, and everything was easy on my head...but with some research I found out it will be a waste of time, because I can't use two varargs on the same method. The for loop idea works, but I can't figure out how to pass only the right String and the right Char. How should I pass them to the method, without passing them both?
Edit: No, this is not a duplicate. I allow loops, the other question doesn't. Also, my problem is about how am I supposed to pass multiple variables, but then using just some. That's an example:
The strings are both long 50, so the method needs to use only 'first' as String, and 'firstChar' as Char.

You can use String.indexOf().
returns the index within this string of the first occurrence of the
specified character. If a character with value ch occurs in the
character sequence represented by this String object, then the index
(in Unicode code units) of the first such occurrence is returned, if
no such character occurs in this string, then -1 is returned.
public static boolean find(String str, char ch){
if(str.indexOf(ch) == -1)
return false;
return true;
}
As you are thinking, you don't need four parameters for this function. You can use this function with two parameters for both cases:
goal = find(first, firstChar);
goal = find(second, lastChar);
EDIT I think you have misunderstood the way the parameters are mapped.
if you have a function like
public static boolean find(String str, char ch){
//do something
}
You don't need to call the find with same parameters str and ch, I mean find(str,ch). You can call them with any parameter, with any name, like :
goal = find(s,c); // s is a string and c is a char
goal = find(a,b); // a is a string and b is a char
when you call find(s,c), s will be mapped to the first argument in your function that is str and c will be mapped to your second argument that is ch.
This is the reason you are able to call both find(first, firstChar) and find(second, lastChar) with a single function.

private static boolean find(String str, char Char) {
for(int i=0;i<str.length();i++)
if(str.charAt(i)==Char)
return true;
return false;
}
This would help hopefully...

Seems like what you are looking for is:
if (second.indexOf(c) == -1) return false; //char c not found
return true;

Find will simply contain
private boolean find(String subject, char first) {
return subject.indexOf(first) > -1;
}

Related

Java string recursion

I am trying to learn Java, and now I'm trying algorithms. So, I'm stucked on recursion. I have a code that I don't understand.
public static String reverseString(String text){
// base case
if (text.length() == 0) {
return text;
}
else {
// recursive call
return reverseString(text.substring(1)) + text.charAt(0);
}
}
public static void main(String[] args) {
String str = new String("howdy");
// calling recursive function
String reverse = reverseString(str);
System.out.println(reverse); // Prints: ydwoh
}
Problem is that for me recursive call in this code for me is:
for the first time it retuns owdyh,
second time wdyo and so on.
I can't understand how the string ydwoh borns. I suspect that somewhere chars concotanating in the right order, and stored somewhere, but where is this place I also don't know.
UPDATE
I tried it with paper, what I got:
first recursive call:
return value owdyh = "owdy" + "h"
second call:
return value wdyo = "wdy" + "o"
and so on
The difficulty is the processing after the call. The first letter is added to the end of the result of reverseString of the rest.
reverseString "howdy"
reverseString "owdy"
reverseString "wdy"
reverseString "dy"
reverseString "y"
reverseString ""
return ""
return "" + "y"
returns "y" + "d"
returns "yd" + "w"
returns "ydw" + "o"
returns "ydwo" + "h"
returns "ydwoh"
It is like a mathematical proof by induction:
The empty string is reversed (result empty string).
When the recursive call works on a smaller string,
placing the first char at the end, also reverses the string.
So reverseString works for all length of strings.
Thanks for the answers! They helped me to figure out my misunderstanding!
What I couldn't understand is where all the chars from the text.charAt(0) are stored! The trick is that they are stored in the stack without any links. It's LIFO(Last-In-First-Out) approach in work.

How do I check if one string contains characters from another string?

I want to create a boolean method that allows me to check if the characters in one string randomly generated in a method before contains characters from a string that the user inputs.
Example:
Random base word: Cellphone
User word: Cell --> Yes this is okay.
User word: Cells --> No, it contains letters not found in original word given.
I'm thinking we can maybe do something that looks like this:
public static class boolean usesSymbolsFromWord(String candidate, String base) {
//pseudocode
characters in String candidate are found in String base
return true;
}
return false;
}
Just try it with a build in method of Java.lang.String:
base.contains(candidate);
That's all.
For further informations see the Java Docs:
contains(CharSequence s)
Returns true if and only if this string
contains the specified sequence of char values.
try this func
boolean allS1CharsAreInS2(String s1, String s2) {
for(int i = 0; i < s1.length(); i++) {
char c = s1.charAt(i);
if (s2.indexOf(c) == -1) {
return false;
}
}
return true;
}
I normally use : word1.toUpperCase().contains(word2.toUpperCase()) as I prefer case insensitive check. But its based on your requirement. If it has to be case sensitive checking, you can use word1.contains(word2)

Java codingbat help - withoutString

I'm using codingbat.com to get some java practice in. One of the String problems, 'withoutString' is as follows:
Given two strings, base and remove, return a version of the base string where all instances of the remove string have been removed (not case sensitive).
You may assume that the remove string is length 1 or more. Remove only non-overlapping instances, so with "xxx" removing "xx" leaves "x".
This problem can be found at: http://codingbat.com/prob/p192570
As you can see from the the dropbox-linked screenshot below, all of the runs pass except for three and a final one called "other tests." The thing is, even though they are marked as incorrect, my output matches exactly the expected output for the correct answer.
Here's a screenshot of my output:
And here's the code I'm using:
public String withoutString(String base, String remove) {
String result = "";
int i = 0;
for(; i < base.length()-remove.length();){
if(!(base.substring(i,i+remove.length()).equalsIgnoreCase(remove))){
result = result + base.substring(i,i+1);
i++;
}
else{
i = i + remove.length();
}
if(result.startsWith(" ")) result = result.substring(1);
if(result.endsWith(" ") && base.substring(i,i+1).equals(" ")) result = result.substring(0,result.length()-1);
}
if(base.length()-i <= remove.length() && !(base.substring(i).equalsIgnoreCase(remove))){
result = result + base.substring(i);
}
return result;
}
Your solution IS failing AND there is a display bug in coding bat.
The correct output should be:
withoutString("This is a FISH", "IS") -> "Th a FH"
Yours is:
withoutString("This is a FISH", "IS") -> "Th a FH"
Yours fails because it is removing spaces, but also, coding bat does not display the correct expected and run output string due to HTML removing extra spaces.
This recursive solution passes all tests:
public String withoutString(String base, String remove) {
int remIdx = base.toLowerCase().indexOf(remove.toLowerCase());
if (remIdx == -1)
return base;
return base.substring(0, remIdx ) +
withoutString(base.substring(remIdx + remove.length()) , remove);
}
Here is an example of an optimal iterative solution. It has more code than the recursive solution but is faster since far fewer function calls are made.
public String withoutString(String base, String remove) {
int remIdx = 0;
int remLen = remove.length();
remove = remove.toLowerCase();
while (true) {
remIdx = base.toLowerCase().indexOf(remove);
if (remIdx == -1)
break;
base = base.substring(0, remIdx) + base.substring(remIdx + remLen);
}
return base;
}
I just ran your code in an IDE. It compiles correctly and matches all tests shown on codingbat. There must be some bug with codingbat's test cases.
If you are curious, this problem can be solved with a single line of code:
public String withoutString(String base, String remove) {
return base.replaceAll("(?i)" + remove, ""); //String#replaceAll(String, String) with case insensitive regex.
}
Regex explaination:
The first argument taken by String#replaceAll(String, String) is what is known as a Regular Expression or "regex" for short.
Regex is a powerful tool to perform pattern matching within Strings. In this case, the regular expression being used is (assuming that remove is equal to IS):
(?i)IS
This particular expression has two parts: (?i) and IS.
IS matches the string "IS" exactly, nothing more, nothing less.
(?i) is simply a flag to tell the regex engine to ignore case.
With (?i)IS, all of: IS, Is, iS and is will be matched.
As an addition, this is (almost) equivalent to the regular expressions: (IS|Is|iS|is), (I|i)(S|s) and [Ii][Ss].
EDIT
Turns out that your output is not correct and is failing as expected. See: dansalmo's answer.
public String withoutString(String base, String remove) {
String temp = base.replaceAll(remove, "");
String temp2 = temp.replaceAll(remove.toLowerCase(), "");
return temp2.replaceAll(remove.toUpperCase(), "");
}
Please find below my solution
public String withoutString(String base, String remove) {
final int rLen=remove.length();
final int bLen=base.length();
String op="";
for(int i = 0; i < bLen;)
{
if(!(i + rLen > bLen) && base.substring(i, i + rLen).equalsIgnoreCase(remove))
{
i +=rLen;
continue;
}
op += base.substring(i, i + 1);
i++;
}
return op;
}
Something things go really weird on codingBat this is just one of them.
I am adding to a previous solution, but using a StringBuilder for better practice. Most credit goes to Anirudh.
public String withoutString(String base, String remove) {
//create a constant integer the size of remove.length();
final int rLen=remove.length();
//create a constant integer the size of base.length();
final int bLen=base.length();
//Create an empty string;
StringBuilder op = new StringBuilder();
//Create the for loop.
for(int i = 0; i < bLen;)
{
//if the remove string lenght we are looking for is not less than the base length
// and the base substring equals the remove string.
if(!(i + rLen > bLen) && base.substring(i, i + rLen).equalsIgnoreCase(remove))
{
//Increment by the remove length, and skip adding it to the string.
i +=rLen;
continue;
}
//else, we add the character at i to the string builder.
op.append(base.charAt(i));
//and increment by one.
i++;
}
//We return the string.
return op.toString();
}
Taylor's solution is the most efficient one, however I have another solution that is a naive one and it works.
public String withoutString(String base, String remove) {
String returnString = base;
while(returnString.toLowerCase().indexOf(remove.toLowerCase())!=-1){
int start = returnString.toLowerCase().indexOf(remove.toLowerCase());
int end = remove.length();
returnString = returnString.substring(0, start) + returnString.substring(start+end);
}
return returnString;
}
#Daemon
your code works. Thanks for the regex explanation. Though dansalmo pointed out that codingbat is displaying the intended output incorrectly, I through in some extra lines to your code to unnecessarily account for the double spaces with the following:
public String withoutString(String base, String remove){
String result = base.replaceAll("(?i)" + remove, "");
for(int i = 0; i < result.length()-1;){
if(result.substring(i,i+2).equals(" ")){
result = result.replace(result.substring(i,i+2), " ");
}
else i++;
}
if(result.startsWith(" ")) result = result.substring(1);
return result;
}
public String withoutString(String base, String remove){
return base.replace(remove,"");
}

Java check all characters in string are present in a given string array

I am attempting to create a method that checks every character in userInput to see if they are present in operatorsAndOperands. The issue is that tempbool is always false for all values.
import java.util.*;
public class stringCalculator
{
private String userInput = null;
String[] operatorsAndOperands = {"1","2","3","4","5","6","7","8","9","0","+","-","*","/"};
public stringCalculator(String newInput)
{
userInput = newInput;
}
public boolean checkInput()
{
boolean ifExists = true;
for(int i=0; i<userInput.length(); i++)
{
char currentChar = userInput.charAt(i);
boolean tempbool = Arrays.asList(operatorsAndOperands).contains(currentChar);
if (tempbool == false)
{
ifExists = false;
}
}
return ifExists;
}
}
This is because you have an array of string objects (which you later convert to a list of string objects), but you are checking a char for presence in that array.
Efficiency is also pretty poor here - converting a fixed array to a list on each iteration takes a lot of unnecessary CPU cycles.
A simple solution to this problem is to put all characters in a string, and then check each incoming character against that string:
if ("0123456789+-*/".indexOf(currentChar) >= 0) {
... // Good character
}
Another solution would be making a regex that allows only your characters to be specified, like this:
if (expr.replaceAll("[0-9+/*-]*", "").length() == 0) {
... // Expr contains only valid characters
}
Why don't you declare
String[] operatorsAndOperands = {"1","2","3","4","5","6","7","8","9","0","+","-","*","/"};
as a String, instead of an array of String. Then you can just use the contains method to check the characters against the valid operators.
Declare: char[] operatorsAndOperands; instead of: String[] operatorsAndOperands.
Or add this: String.valueOf(charToCompare) as the "contains" argument.
As has been pointed out, the issue is that you're checking for a char in a list of String objects, so you'll never find it.
You can make this check easier, though, by using a regular expression:
Pattern operatorsAndOperands = Pattern.compile("[0-9+\\-*/]");

In Java, how to find if first character in a string is upper case without regex

In Java, find if the first character in a string is upper case without using regular expressions.
Assuming s is non-empty:
Character.isUpperCase(s.charAt(0))
or, as mentioned by divec, to make it work for characters with code points above U+FFFF:
Character.isUpperCase(s.codePointAt(0));
Actually, this is subtler than it looks.
The code above would give the incorrect answer for a lower case character whose code point was above U+FFFF (such as U+1D4C3, MATHEMATICAL SCRIPT SMALL N). String.charAt would return a UTF-16 surrogate pair, which is not a character, but rather half the character, so to speak. So you have to use String.codePointAt, which returns an int above 0xFFFF (not a char). You would do:
Character.isUpperCase(s.codePointAt(0));
Don't feel bad overlooked this; almost all Java coders handle UTF-16 badly, because the terminology misleadingly makes you think that each "char" value represents a character. UTF-16 sucks, because it is almost fixed width but not quite. So non-fixed-width edge cases tend not to get tested. Until one day, some document comes in which contains a character like U+1D4C3, and your entire system blows up.
There is many ways to do that, but the simplest seems to be the following one:
boolean isUpperCase = Character.isUpperCase("My String".charAt(0));
Don't forget to check whether the string is empty or null. If we forget checking null or empty then we would get NullPointerException or StringIndexOutOfBoundException if a given String is null or empty.
public class StartWithUpperCase{
public static void main(String[] args){
String str1 = ""; //StringIndexOfBoundException if
//empty checking not handled
String str2 = null; //NullPointerException if
//null checking is not handled.
String str3 = "Starts with upper case";
String str4 = "starts with lower case";
System.out.println(startWithUpperCase(str1)); //false
System.out.println(startWithUpperCase(str2)); //false
System.out.println(startWithUpperCase(str3)); //true
System.out.println(startWithUpperCase(str4)); //false
}
public static boolean startWithUpperCase(String givenString){
if(null == givenString || givenString.isEmpty() ) return false;
else return (Character.isUpperCase( givenString.codePointAt(0) ) );
}
}
Make sure you first check for null and empty and ten converts existing string to upper. Use S.O.P if want to see outputs otherwise boolean like Rabiz did.
public static void main(String[] args)
{
System.out.println("Enter name");
Scanner kb = new Scanner (System.in);
String text = kb.next();
if ( null == text || text.isEmpty())
{
System.out.println("Text empty");
}
else if (text.charAt(0) == (text.toUpperCase().charAt(0)))
{
System.out.println("First letter in word "+ text + " is upper case");
}
}
If you have to check it out manually you can do int a = s.charAt(0)
If the value of a is between 65 to 90 it is upper case.
we can find upper case letter by using regular expression as well
private static void findUppercaseFirstLetterInString(String content) {
Matcher m = Pattern
.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(
content);
System.out.println("Given input string : " + content);
while (m.find()) {
if (m.group(1).equals(m.group(1).toUpperCase())) {
System.out.println("First Letter Upper case match found :"
+ m.group());
}
}
}
for detailed example . please visit http://www.onlinecodegeek.com/2015/09/how-to-determines-if-string-starts-with.html
String yourString = "yadayada";
if (Character.isUpperCase(yourString.charAt(0))) {
// print something
} else {
// print something else
}

Categories