I have a string like
Str s1 = abd,jh
Str2 = aa$$ab
I want to read string which have only a,b and $.
Str1 return false
Str2 return true.
My Code
public static boolean containsOtherCharacter(String str) {
String[] st = str.split("");
for(int x = 0; x < st.length; x++)
if (st[x].compareTo("A") != 0 && st[x].compareTo("B") != 0 && st[x].compareTo("$") != 0)
return true;
return false;
}
Any help how to read that. Any other value other then this should be ignored.
You're trying to overcomplicate things here. You could simply use a regular expression, like
String s = "aa$$ab";
System.out.println(s.replaceAll("[ab$]", "").length()==0);
It removes a, $, and b from the String. After that, if the length is greater than 0, then the String must have had some other characters.Note that it is case sensitive.
public static boolean hasSpecialChar( String input)
{
boolean found = true;
int len = input.length();
for(int i = 0; i< len ; i++)
{
if(input.charAt(i)== 97|| input.charAt(i)==98 ||input.charAt(i)==36)
{
// read the string
}
else
{
found = false;
return found;
// give out the error
}
}
return found ;
}
As you want to only read the a, b and $ thus we could use the ASCII values of the character and thus read in the string or line character by character and check the input. As the ASCII values for a is equal to 97, 98 for b and 36 for $ this would work fine for this case.
Hope is helps you!!! #shanky singh
Here's another way to solve this:
public static boolean containsOtherCharacter(String str) {
boolean The_answer=false;
int count0 = StringUtils.countMatches(str, "a");
int count1 = StringUtils.countMatches(str, "b");
int count2 = StringUtils.countMatches(str, "$");
int ans=count0+count1+count2;
if(ans==str.length())The_anser=true;
return The_answer;
}
Related
Here's the code that I attempted
public String isPalindrome(String s) {
String trimmed = s.replaceAll("[^A-Za-z0-9]", "");
String reversed = "";
int len = trimmed.length();
for (int i = len - 1; i >= 0; i--) {
char[] allChars = trimmed.toCharArray();
reversed += allChars[i];
}
if (trimmed.equalsIgnoreCase(reversed)) {
return "true";
} else {
return "false";
}
}
Sample Input 1
A man, a plan, a canal: Panama
Sample Output 1
true
Explanation 1
The given string is palindrome when considering only alphanumeric characters.
Sample Input 2
race a car
Sample Output 2
false
Explanation 2
The given string is not a palindrome when considering alphanumeric characters.
Your variable len comes from the length of the String s. But you use the value on the array coming from trimmed.
So if you want to remove the IndexOutOfBoundsException you should change your len declaration to:
int len = trimmed.length();
You can return boolean instead of String:
public static boolean isPalindrome(String s) {
String trimmed = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
int from = 0, to = trimmed.length() - 1;
while (from < to) {
if (trimmed.charAt(from) != trimmed.charAt(to)) {
return false;
}
from++;
to--;
}
return true;
}
You can use StringBuilder to reverse a String:
public static void main(String[] args) {
String input = "a#b!b^a";
String clean = input.replaceAll("[^A-Za-z0-9]", "");
String reverse = new StringBuilder(clean).reverse().toString();
boolean isPalindrome = reverse.equals(clean);
System.out.println(isPalindrome);
}
You can do like this in linear time as the loops are driven by the presence of non-alphabetic/digit characters. Also, no trimming or reversal of the string is required.
String[] test = {"A man, a plan, a canal: Panama",
"race a car","foobar", "ABC2CEc2cba"};
for (String s : test) {
System.out.printf("%5b -> %s%n", isPalindrome(s), s);
}
prints
true -> A man, a plan, a canal: Panama
false -> race a car
false -> foobar
true -> ABC2CEc2cba
The outer while loop drives then entire process until the indices cross or are equal. The inner loops simply skip over non-alphabetic/digit characters.
public static boolean isPalindrome(String s) {
int k = s.length() - 1;
int i = 0;
char c1 = '#';
char c2 = '#';
while (i <= k) {
while (!Character.isLetterOrDigit(c1 = s.charAt(i++)));
while (!Character.isLetterOrDigit(c2 = s.charAt(k--)));
if (Character.toLowerCase(c1) != Character.toLowerCase(c2)) {
return false;
}
}
return true;
}
Example: String a = "ACAHBBA" and String b = "ABAB" should return true, since both strings can spell ABAB.
I have tried with contains(), but that only works for equal sequences.
// The code should look like this.
public class task10 {
public static boolean contains(String a, String b) {
// check if b can be spelled using characters from a.
// if it can. return true.
// else
return false;
}
}
Posible solution?
public static boolean contains(String a, String b) {
for (int i = 0; i < b.length(); i++) {
if (a.indexOf(b.charAt(i)) == -1) {
return false;
}
}
return true;
}
Simply iterate thru one string and get the index of the character. If >= 0, replace character with non-alphabetic character and repeat. This algorithm presumes the need to match the correct number of characters. For example, hello would return false if the character set was helo.
public static boolean spelledFrom(String word, String chars) {
StringBuilder sb = new StringBuilder(chars);
for (String c : word.split("")) {
int i;
if ((i = sb.indexOf(c)) < 0) {
return false;
}
sb.setCharAt(i, '#');
}
return true;
}
You can try this:
public static boolean canSpell(String a, String b)
{
String shorter = (a.length() <= b.length()) ? a : b;
String longer = (shorter.equals(a)) ? b : a;
for(int i = 0; i < shorter.length(); i++)
{
if(!longer.contains("" + shorter.charAt(i)))
return false;
}
return true;
}
Once you've identified the shorter string, you just need to verify that each of its chars are contained in the longer string. This solution doesn't verify if a char "has already been used", which means inserting "AB" and "ABBA" will return true. If you need to do this, you just need to delete the verified char from the longer string in every loop.
Problem: Remove the substring t from a string s, repeatedly and print the number of steps involved to do the same.
Example: t = ab, s = aabb. In the first step, we check if t is contained within s. Here, t is contained in the middle i.e. a(ab)b. So, we will remove it and the resultant will be ab and increment the count value by 1. We again check if t is contained within s. Now, t is equal to s i.e. (ab). So, we remove that from s and increment the count. So, since t is no more contained in s, we stop and print the count value, which is 2 in this case.
I tried to solve this using recursion
static int maxMoves(String s, String t) {
if ( null == s || "" == s || null == t || "" == t){
return 0;
}
int i = s.indexOf(t);
if(i != -1) {
return maxMoves(s.substring(0, i)+ s.substring(i+t.length(), s.length()), t) + 1;
} else {
return 0;
}
}
But I am only passing 9/14 test cases. I also tried this,
static int maxMoves(String s, String t) {
int count = 0,i;
while(true)
{
if(s.contains(t))
{
i = s.indexOf(t);
s = s.substring(0,i) + s.substring(i + t.length());
}
else break;
++count;
}
return count;
}
But that also only passed 9/14 cases.
Could anyone help me figure out which cases I am not covering?
Simply you can use String::replaceFirst with a while loop for example:
String s = "aabb";
String t = "ab";
int count = 0;
while (s.contains(t)) {
s = s.replaceFirst(Pattern.quote(t), "");
count++;
}
System.out.println(count);
Use String#replace
String s = "aabb";
String oldstr = s;
String x = "ab";
while(s.contains(x)){
s = s.replace(x, "");
}
System.out.println((oldstr.length()-s.length())/x.length());
An easy and efficient way is to accumulate the string character-by-character in a StringBuilder; if at any time its buffer ends with the string you want to replace, remove it:
StringBuilder sb = new StringBuilder();
int c = 0;
for (int i = 0; i < s.length(); ++i) {
sb.append(s.charAt(i));
int last = sb.length()-t.length();
if (last >= 0 && sb.indexOf(t, last) == last) {
sb.setLength(last);
++c;
}
}
// c is now the number of times you removed t from s.
public static boolean isValidNumber(String a1)
{
String x = ("0123456789");
boolean valid = false;
for (int i = 0; i < 4; i++) {
char c = a1.charAt(i);
for (int j = 0; j < 10; j++) {
if ( c == x.charAt(j)) {
valid = true;
}
else {
valid = false;
}
}
}
return valid;
}
The above method checks to see whether an input of a four character string is composed of the characters 0123456789. However, regardless of what the input is, the method always returns as false.
If I were to change the valid value in the else statement to true, the method would always return as true.
What is the error that I have made in this method?
As soon as you find a non matching character, break the loop otherwise the next matching character will set valid to true.
e.g. "123a456" is considered valid.
for (int j = 0; j < 10; j++) {
if ( c == x.charAt(j)) {
valid = true;
}
else {
valid = false;
break;
}
}
If for some reason you don't want to break the loop, you could keep an "invalid counter" and make sure that is 0 at the end.
Of course for what you are doing here, Integer.parseInt() might be your best bet ;-)
a String.equals method will check these two strings in a single statement if you are permitted to use that.
public static boolean isValidNumber(String a1)
{
String x = ("0123456789");
return x.equals(a1);
}
I would rewrite your function as given below,
String x = ("0123456789");
boolean valid = false;
for (int i = 0; i < 4; i++) {
char c = a1.charAt(i);
boolean isCharOK = false;
for (int j = 0; j < 10; j++) {
if ( c == x.charAt(j)) {
isCharOK = true;
break;
}
}
if (!isCharOK) {
valid = false;
break;
}
}
return valid;
John3136 is quite correct, but I would like to propose even better solution to your whole task:
final static String x = "0123456789";
public static boolean isValidNumber(String a1) {
for (int i = 0; i < a1.length(); ++i) {
if (x.indexOf(a1.charAt(i)) == -1) return false;
}
return true;
}
In short: the above code "looks up" every character in your parameter string a1 in the string composed of digits. If it can find it, continues. If it can't, it means a1 consist not only digits and returns false. If it passes through all a1 characters then it returns true :)
And as asked and described in the comments - handling of duplicate characters in argument string:
final static String x = "0123456789";
public static boolean isValidNumber(String a1) {
for (int i = 0; i < a1.length(); ++i) {
final char currentChar = a1.charAt(i);
if (x.indexOf(currentChar) == -1 || a1.indexOf(currentChar, i+1) != -1)
return false;
}
return true;
}
The function call a1.indexOf(currentChar, i+1) essentially checks if there is any duplicate character in the rest of the string (from position i+1 and farther). Which means if it will be able to find duplicate char, the method return false :) Hope this helps, here is more info on String.indexOf(int, int) function if you want:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int, int)
You can use this one liner function to check for validity of a String as Number using Regular Expression
public static boolean isValidNumber(String a1)
{
return a1.matches("[\\d]+");
}
Hope this helps.
I have an issue with a string compare problem...
lets say: string a = "0123456789ABCDEF" string b = "00CC0G"
how do i loop a java code so i can check string a for match with each letter from string b. While comparing the match, the letter from string b has to go thru the entire loop against string a before deciding if there is a match or not. if a match is found it should check the next letter in string b against string a and so on until the last letter in string b. if no match is found, the function shud exit the loop and return false. otherwise if each letter in string b is a match atleast once with string a, the function shud return true.
Example... the function should return false, because the first 5 letters match but the last one doesnt.
any idea? Thanks
EDIT: what i have so far
public boolean checkVal(String b) {
// b = "00CC0G";
String a = "0123456789ABCDEF";
String toUC = b.toUpperCase();
char[] cArray = toUC.toCharArray();
char[] vArray = a.toCharArray();
int j = 0;
int m = 0;
for (int i = 0; i <=cArray.length(); i++) {
for (int k = 0; k <= vArray.length(); k++) {
if (cArray[k] == vArray[i]) {
j++;
}
else {
m--;
break; //loop should exit if there is a non match and function should return false
}
}
}
if (j > 0) return true; //string a matched atleast once with string b
if (m < 0) return false; //string a alteast has one NO MATCH with string b
}
The looping is what getting me confused...
Spoonfeeding since 2k12.
public static boolean isValid(String a, String b){
for(char c : b.toCharArray())
if(!a.contains(""+c))
return false;
return true;
}