This question already has answers here:
How can I check if a single character appears in a string?
(16 answers)
Closed 5 years ago.
java: incompatible types: char cannot be converted to java.lang.CharSequence
boolean checkParentheses(String str) {
Deque<Character> stack = new ArrayDeque<>();
String k = "({[";
String s = ")]}";
for (int i = 0; i < str.length();i++ ) {
if (k.contains(str.charAt(i))) {
stack.push(str.charAt(i));
} else if (s.contains(str.charAt(i))) {
if (matching(stack.peek()) == str.charAt(i)) {
return true;
}
} else {
return false;
}
}
}
what should I use instead of contains?
indexOf with -1.
Something along these lines:
boolean checkParentheses(String str) {
Deque<Character> stack = new ArrayDeque<>();
String k = "({[";
String s = ")]}";
for (int i = 0; i < str.length();i++ ) {
if (k.indexOf(str.charAt(i)) > -1) {
stack.push(str.charAt(i));
} else if (s.indexOf(str.charAt(i)) > -1) {
if (matching(stack.peek()) == str.charAt(i)) {
return true;
}
} else {
return false;
}
}
return false;
}
You could also use contains creating a new String. But that option is not that good (more ineficcient).
2nd option:
boolean checkParentheses(String str) {
Deque<Character> stack = new ArrayDeque<>();
String k = "({[";
String s = ")]}";
for (int i = 0; i < str.length(); i++) {
if (k.contains(String.valueOf(str.charAt(i)))) {
stack.push(str.charAt(i));
} else if (s.contains(String.valueOf(str.charAt(i)))) {
if (matching(stack.peek()) == str.charAt(i)) {
return true;
}
} else{
return false;
}
}
return false;
}
The second option is rather ugly.
Try using indexOf instead of contains. Contains requires a String (AKA CharSequence), but you have a char. Also you can refer : https://javamanikandan.blogspot.in/2018/01/java-string-indexof-method-example.html
and
https://javamanikandan.blogspot.in/2018/01/java-string-contains-method-explained.html
Try this
k.contains(""+str.charAt(i))
the method contains works with String objects not Char
Related
I have these two methods- My code doesn't seem to be working as planned
What is is supposed to do is- Go through the array of characters- If there's not another character the same in the array, it is supposed to add itself to the index variable-
This is my comparing method
private boolean isValid(char c) {
for(int i = 0; i < letters.length; i++) {
if(Arrays.asList(letters).equals(c)) {
return false; //Not valid
}
}
return true;
Full code is below though
public void generate(String first, String second) {
tempString = new StringBuilder(first+second).reverse();
letters = new char[tempString.length()];
for(int i = 0; i < tempString.length(); i++) {
letters[i]= tempString.charAt(i);
if(isValid(tempString.charAt(i))) {
index += i;
}
}
}
private boolean isValid(char c) {
for(int i = 0; i < letters.length; i++) {
if(Arrays.asList(letters).equals(c)) {
return false; //Not valid
}
}
return true;
}
There is no need to convert to a List (and a List is not a primitive char), you can use == for comparing primitive values (such as your chars). Something like,
private boolean isValid(char c) {
for (int i = 0; i < letters.length; i++) {
if (letters[i] == c) {
return false;
}
}
return true;
}
or with an enhanced for-each loop like
private boolean isValid(char c) {
for (char letter : letters) { // <-- for each letter in letters.
if (letter == c) { // <-- if the letter is equal to the argument.
return false;
}
}
return true;
}
You should also test for validity before adding to the array like
if (isValid(tempString.charAt(i))) {
letters[index] = tempString.charAt(i);
index++;
}
Arrays.asList(letters).equals(c) is comparing the list to the character (Is the list equal to this character which is not what you want.
To find if a character is in the string you can instead do
string.indexOf('a') which will return -1 if the character is not present and >= 0 if it is in the string.
I have a method that's supposed to validate accurate opening and closing parenthesis in a string using java. This method will be used to parse mathematical expressions so it's important for the parenthesis to be balanced. For some reason, it is returning false in both of these runs:
System.out.println(parChecker("(()")); // returns false :-)
System.out.println(parChecker("((()))")); // returns false :-( WHY??
Here is the method that uses a stack to solve the problem. Something is wrong here becuase it's returning false for a balanced set of parenthesis as well. What's the problem? Thank you in advance.
public static boolean parChecker(String str) {
String[] tokens = str.split("");
int size = tokens.length;
Stack theStack = new Stack(size);
int index = 0;
boolean balanced = true;
while ((index < size) && balanced) {
String symbol = tokens[index];
if (symbol.equals("(")) {
theStack.push(symbol);
} else {
if (theStack.isEmpty()) {
balanced = false;
} else {
theStack.pop();
}
}
index++;
}
if (balanced && theStack.isEmpty()) {
return true;
} else {
return false;
}
}
Here is my stack class that I'm using:
public class Stack {
private Object [] stack;
private int maxSize = 0;
private int top;
public Stack(int size){
maxSize = size;
stack = new Object[maxSize];
top = -1;
}
public void push(Object obj){
top++;
stack[top] = obj;
}
public Object pop(){
return stack[top--];
}
public Object peek(){
return stack[top];
}
public boolean isEmpty(){
return (top == -1);
}
public boolean isFull(){
return (top == maxSize -1);
}
}
The immediate problem is this
String[] tokens = str.split("");
Gives you first char = "" if you use java 1.7 or less, so you will exit your loop since stack is empty...
Note: this has been changed in java 1.8 split difference between java 1.7 and 1.8
change to:
char[] tokens = str.toCharArray();
I guess however that you need to consider the fact that there can be chars before your first ( and that you may have other chars then ( and )
As far as I can tell, there is no problem with the code (turns out it's a Java 7 specific issue..).
I would like to offer a replacement method though, for educational purposes, that is shorter, and and is tolerant of other characters being present:
public static boolean parChecker(String str) {
Stack stack = new Stack(str.length());
for (char c : str.toCharArray())
switch (c) {
case '(':
stack.push(c);
break;
case ')':
if (stack.isEmpty() || stack.pop() != Character.valueOf('('))
return false;
}
return stack.isEmpty();
}
As requested, here's another solution that doesn't use a stack:
public static boolean parChecker(String str) {
str = str.replaceAll("[^()]", "");
while (str.contains("()"))
str = str.replace("()", "");
return str.isEmpty();
}
And one more for the road: #FredK's algorithm:
public static boolean parChecker(String str) {
int depth = 0;
for ( char c : str.toCharArray() )
if ( ( depth += c == '(' ? 1 : c == ')' ? -1 : 0 ) < 0 )
return false;
return depth == 0;
}
This question already has answers here:
How to check if a String is numeric in Java
(41 answers)
Closed 6 years ago.
I have a gpa program, and it works with the equalsIgnoreCase() method which compares two strings, the letter "a" to the user input, which checks if they put "a" or not. But now I want to add an exception with an error message that executes when a number is the input. I want the program to realize that the integer input is not the same as string and give an error message. Which methods can I use to compare a type String variable to input of type int, and throw exception?
Many options explored at http://www.coderanch.com/t/405258/java/java/String-IsNumeric
One more is
public boolean isNumeric(String s) {
return s != null && s.matches("[-+]?\\d*\\.?\\d+");
}
Might be overkill but Apache Commons NumberUtils seems to have some helpers as well.
If you are allowed to use third party libraries, suggest the following.
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/math/NumberUtils.html
NumberUtils.isDigits(str:String):boolean
NumberUtils.isNumber(str:String):boolean
Use this
public static boolean isNum(String strNum) {
boolean ret = true;
try {
Double.parseDouble(strNum);
}catch (NumberFormatException e) {
ret = false;
}
return ret;
}
You can also use ApacheCommons StringUtils.isNumeric - http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isNumeric(java.lang.String)
Simple method:
public boolean isBlank(String value) {
return (value == null || value.equals("") || value.equals("null") || value.trim().equals(""));
}
public boolean isOnlyNumber(String value) {
boolean ret = false;
if (!isBlank(value)) {
ret = value.matches("^[0-9]+$");
}
return ret;
}
Use below method,
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
If you want to use regular expression you can use as below,
public static boolean isNumeric(String str)
{
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
public static boolean isNumeric(String string) {
if (string == null || string.isEmpty()) {
return false;
}
int i = 0;
int stringLength = string.length();
if (string.charAt(0) == '-') {
if (stringLength > 1) {
i++;
} else {
return false;
}
}
if (!Character.isDigit(string.charAt(i))
|| !Character.isDigit(string.charAt(stringLength - 1))) {
return false;
}
i++;
stringLength--;
if (i >= stringLength) {
return true;
}
for (; i < stringLength; i++) {
if (!Character.isDigit(string.charAt(i))
&& string.charAt(i) != '.') {
return false;
}
}
return true;
}
I wrote this little method lastly in my program so I can check if a string is numeric or at least every single char is a number.
private boolean isNumber(String text){
if(text != null || !text.equals("")) {
char[] characters = text.toCharArray();
for (int i = 0; i < text.length(); i++) {
if (characters[i] < 48 || characters[i] > 57)
return false;
}
}
return true;
}
You can use Character.isDigit(char ch) method or you can also use regular expression.
Below is the snippet:
public class CheckDigit {
private static Scanner input;
public static void main(String[] args) {
System.out.print("Enter a String:");
input = new Scanner(System.in);
String str = input.nextLine();
if (CheckString(str)) {
System.out.println(str + " is numeric");
} else {
System.out.println(str +" is not numeric");
}
}
public static boolean CheckString(String str) {
for (char c : str.toCharArray()) {
if (!Character.isDigit(c))
return false;
}
return true;
}
}
Here's how to check if the input contains a digit:
if (input.matches(".*\\d.*")) {
// there's a digit somewhere in the input string
}
To check for all int chars, you can simply use a double negative.
if (!searchString.matches("[^0-9]+$")) ...
[^0-9]+$ checks to see if there are any characters that are not integer, so the test fails if it's true. Just NOT that and you get true on success.
Consider you have been told to implement a kind of the java String.substring method.
The signature of the method is as follows:
public static boolean isSubstring(String i_StringForSearch, String i_SubStringToFind)
Here is my solution, but I feel it's still not the best elegant solution I could have.(Many canonical if else's)
What do you think? Would you do it in another way?
public static boolean isSubstring(String i_StringForSearch, String i_SubStringToFind)
{
int strForSearchIndex = 0;
int subStrToFindIndex = 0;
boolean endOfStringToSearch = false;
boolean foundSubString = false;
boolean isThereASequenceOfMatching = false;
while(!endOfStringToSearch && !foundSubString)
{
if(strForSearchIndex == i_StringForSearch.length())
{
endOfStringToSearch = true;
}
else if(i_StringForSearch.charAt(strForSearchIndex) == i_SubStringToFind.charAt(subStrToFindIndex))
{
isThereASequenceOfMatching = true;
if(subStrToFindIndex == i_SubStringToFind.length() -1 )
{
foundSubString = true;
}
subStrToFindIndex++;
strForSearchIndex++;
}
else if(i_StringForSearch.charAt(strForSearchIndex) != i_SubStringToFind.charAt(subStrToFindIndex))
{
if(isThereASequenceOfMatching)
{
subStrToFindIndex = 0;
isThereASequenceOfMatching = false;
}
strForSearchIndex++;
}
}
return foundSubString;
}
Look up the Boyer-Moore and Knuth-Morris-Pratt algorithms. In tests many years ago I found BM to be slightly faster.
public static boolean isSubstring(final String i_StringForSearch, final String i_SubStringToFind) {
int j = 0;
for (int i = 0; i < i_StringForSearch.length(); i++) {
if (i_StringForSearch.charAt(i) == i_SubStringToFind.charAt(j)) {
j++;
if (j == i_SubStringToFind.length()) {
return true;
}
}
}
return false;
}
Hi
I have to compute if a given string is substring of a bigger string.
For example
String str = "Hallo my world";
String substr = "my"
The method "contains" should return true because str contains substr (false otherwise).
I was looking for something like "contains" at the String class
but I didn't find it. I suppose that the only solution is to use
pattern matching. If this is the case which would be the better (cheapest) way
to do this?
Thanks!
There is a contains() method! It was introduced in Java 1.5. If you are using an earlier version, then it's easy to replace it with this:
str.indexOf(substr) != -1
String str="hello world";
System.out.println(str.contains("world"));//true
System.out.println(str.contains("world1"));//false
Javadoc
String s = "AJAYkumarReddy";
String sub = "kumar";
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == sub.charAt(count)) {
count++;
} else {
count = 0;
}
if (count == sub.length()) {
System.out.println("Sub String");
return;
}
}
use indexOf it will return -1 if no match (contains was added in 1.5, maybe you are using older jdk?) see "contains(CharSequence s)" method in String class in JDK 1.4.2 for details
if (str.indexOf(substr) >= 0) {
// do something
}
I think there is a String function that does just what you are asking: String.indexOf(String).
See this link: http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#indexOf(java.lang.String)
So, then you could write this function:
public boolean isSubstring(String super, String sub) {
return super.indexOf(sub) >= 0;
}
String.indexOf(substr) complexity is O(n2).. Luixv asked a cheaper solution.. But as far as , I know there is no better algorithm than current one.
public boolean isSubString(String smallStr, String largerStr) {
char[] larger = largerStr.toCharArray();
char[] smaller = smallStr.toCharArray();
int i = 0;
for (int j = 0; j < larger.length; j++) {
if(larger[j] == smaller[i]){
if(i == smaller.length -1){
//done we found that this string is substring
return true;
}
i++;
continue;
}else{
if(i > 0){
//that means we encountered a duplicate character before and if string was substring
// it shouldn't have hit this condition..
if(larger.length - j >= smaller.length){
i = 0;
//reset i here because there are still more characters to check for substring..
}else{
//we don't have enough characters to check for substring.. so done..
return false;
}
}
}
}
return false;
}
here is a general method that you can use
public static boolean isSubstring(String s1, String s2) {
if(s1.length() == s2.length())
return s1.equals(s2);
else if(s1.length() > s2.length())
return s1.contains(s2);
else
return s2.contains(s1);
}
public static boolean isSubstring(String s1, String s2){
if(s1.length()<s2.length()) return false;
if(s1.length()==s2.length()) return s1.equals(s2);
for(int i=0;i<=s1.length()-s2.length();i++){
if(s1.charAt(i)==s2.charAt(0)){
int matchLength=1;
for(int j=1;j<s2.length();j++){
if(s1.charAt(i+j)!=s2.charAt(j)){
break;
}
matchLength++;
}
if(matchLength==s2.length()) return true;
}
}
return false;
}
This checks if s2 is a substring of s1.
You can use .substring(int beginIndex,int lastIndex) to check this program. Sample code goes as below:-
public class Test {
public static void main(final String[] args) {
System.out.println("Enter the first String");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
String s1 = br.readLine();
System.out.println("Enter the second String");
String s2 = br.readLine();
boolean result = isSubStr(s1, s2);
if (result == true)
System.out.println("The second String is substring of the first String");
else
System.out.println("The second String is not a substring of the first String");
} catch (IOException e) {
System.out.println("Exception Caught: " + e);
}
}
public static boolean isSubStr(String st1, String s2) {
boolean result = false;
String tem_str = "";
int len1 = st1.length();
int i = 0;
int j;
while (i < len1) {
j = i+1;
while (j <=len1) {
tem_str = st1.substring(i, j);
if (tem_str.equalsIgnoreCase(s2)) {
result = true;
break;
}
j++;
}
i++;
}
return result;
}
}
Go through this method.
visit for tricky code
public static boolean isSubString(String s, String sub) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == sub.charAt(count)) {
count++;
} else {
i-=count;
count = 0;
}
if (count == sub.length()) {
return true;
}
}
return false;
}
Consider the following code:
If substring is present then it returns the start index of substring in a given string
Else returns -1
public static int isSubstring(String str, String pattern)
{
int str_length = str.length();
int pattern_length = pattern.length();
for (int i = 0; i <= str_length - pattern_length; i++)
{
int j;
for (j = 0; j < pattern_length; j++)
if (str.charAt(i + j) != pattern.charAt(j))
break;
if (j == pattern_length)
return i;
}
return -1;
}
String str1 = "Java8 makes Java more powerful";
String str2 = "Java";
char c;
char d;
int count=0;
boolean match = true;
for (int i = 0; i < str1.length(); i++) {
c = str1.charAt(i);
for (int j = 0; j < str2.length(); j++) {
d = str2.charAt(j);
if (c == d) {
match = true;
count++;
if(count== str2.length()){
i = str1.length();
break;
}
i++;
c = str1.charAt(i);
} else {
match = false;
}
}
}
if(match == true){
System.out.println("SubString ");
}
public class StringIsSubString {
public static void main(String[] args) {
String s1 = "wel";
String s2 = "12wlecome123";
boolean isSubStr = isSubStr(s1,s2);
System.out.println(isSubStr);
}
private static boolean isSubStr(String s1, String s2) {
String s3 = "";
int j = 0;
if(s1.length() > s2.length()) {
return false;
} else if(s1.equals(s2)){
return true;
} else {
for(int i=0; i<s1.length();i++) {
for(; j<s2.length();j++) {
if(s1.charAt(i) == s2.charAt(j)) {
s3 = s3 + s1.charAt(i);
break;
}
}
}
if(s3.equals(s1)) {
return true;
}
return false;
}
}
}
*In their any sub string will be count by the form of 1th place of string of substring *
int isSubstring(string s1, string s2) {
int M = s1.length();
int N = s2.length();
for (int i = 0; i <= N - M; i++) {
int j;
for (j = 0; j < M; j++)
if (s2[i + j] != s1[j])
break;
if (j == M)
return i;
}
return -1;
}
int main() {
string s1 = "kumar";
string s2 = "abhimanyukumarroy";
int res = isSubstring(s1, s2);
if (res == -1)
cout << "Not present";
else
cout << "Present at index " << res;
return 0;
}