Creating a ubbi dubbi detector in java - java

I am trying to make an ubbi dubbi detector in java. I am currently trying to count how many ub's there are in the string and add them up to a counter and then if there is a certain number under the int I put, then it is not ubbi dubbi, but if it is equal to or above then it is ubbi dubbi. We aren't allowed to use regex, string builder, or arrays.
Here is what I have currently:
public static boolean detect(String phrase) {
boolean isUbbi = false;
int count = 0;
CharSequence ub = "ub";
if (phrase.contains(ub)) {
count++;
}
if (count >= 2) {
isUbbi = true;
} else {
isUbbi = false;
}
return isUbbi;
}

In your case it the condition never met to become true.
Because
if (phrase.contains(ub)) {
count++;
}
And the condition is
if (count >= 2) { // never met. Always false.
That will check the occurrence once and then done.little more implementation is needed to check no of occurrences which involves a loop and sub-string etc..
If you are free to use Apache commons library
use
int count = StringUtils.countMatches(phrase, "ub");
If no libraries ,
String mainString = "ububsdfub";
Pattern pat = Pattern.compile("ub");
Matcher matcher = pat.matcher(mainString);
int count = 0;
while (matcher.find()) {
count += 1;
}
System.out.println(count); // prints 3 since 3 ub's are there.
With basic operation split(internally uses regex)
String mainString = "ububsdfUb";
String occurance = "ub";
System.out.println(mainString.split(occurance, -1).length-1);
Even split not allowed
String mainString = "ububsdfub";
String occurance = "ub";
int index=0;
int count=0;
while ((index = mainString.indexOf(occurance, index)) != -1) {
count++;
index += occurance.length() - 1;
}
System.out.println(count);

You can count the number of occurrences by using String.indexOf(…).
int count=0;
for(int pos=phrase.indexOf(ub); pos>0; pos=phrase.indexOf(ub, pos)+1) count++;
// now count contains the numbers of occurrences of ub in phrase

Here is what I came up with, just added the for loop and all works.
public static boolean detect(String phrase) {
boolean isUbbi = false;
int count = 0;
CharSequence ub = "ub";
for(int i = 0; i < phrase.length(); i++) {
if (phrase.contains(ub)) {
count++;
}
if (count >= 2) {
isUbbi = true;
} else {
isUbbi = false;
}
}
return isUbbi;
}

Related

Palindrome in java

Here what I tried
sample input is "aabaa"
eg: in if condition val[0] = a[4]
if it is equal i stored it in counter variable if it is half of the length it original string it is palindrome
if it is not it is not a palindrome
I tried with my basic knowledge in java if there is any errors let me know
boolean solution(String inputString) {
int val = inputString.length();
int count = 0;
for (int i = 0; i<inputString.length(); i++) {
if(inputString.charAt(i) == inputString.charAt(val-i)) {
count = count++;
if (count>0) {
return true;
}
}
}
return true;
}
How about
public boolean isPalindrome(String text) {
String clean = text.replaceAll("\\s+", "").toLowerCase();
int length = clean.length();
int forward = 0;
int backward = length - 1;
while (backward > forward) {
char forwardChar = clean.charAt(forward++);
char backwardChar = clean.charAt(backward--);
if (forwardChar != backwardChar)
return false;
}
return true;
}
From here
In your version you compare first element with last, second with second last etc.
last element in this case is inputString.length()-1(so need to use 'inputString.charAt(val-i-1)' . If you iterate till end, then the count should be equal to length of the string.
for(int i = 0; i<inputString.length(); i++){
if(inputString.charAt(i) == inputString.charAt(val-i-1)){
count ++;
}
}
return (count==val); //true when count=val
Or alternatlively iterate till the mid point of the array, then count value is val/2.
for(int i = 0; i<inputString.length()/2; i++){
if(inputString.charAt(i) == inputString.charAt(val-i-1)){
count ++;
}
}
return (count==val/2); //true when count=val/2
There's no constraints in the question so let me throw in a more cheesy solution.
boolean isPalindrome(String in)
final String inl = in.toLowerCase();
return new StringBuilder(inl).reverse().toString().equals(inl);
}
A palindrome is a word, sentence, verse, or even a number that reads the same forward and backward. In this java solution, we’ll see how to figure out whether the number or the string is palindrome in nature or not.
Method - 1
class Main {
public static void main(String[] args) {
String str = "Nitin", revStr = "";
int strLen = str.length();
for (int i = (strLen - 1); i >=0; --i) {
revStr = revStr + str.charAt(i);
}
if (str.toLowerCase().equals(revStr.toLowerCase())) {
System.out.println(str + " is a Palindrome String.");
}
else {
System.out.println(str + " is not a Palindrome String.");
}
Method - 2
class Main {
public static void main(String[] args) {
int n = 3553, revNum = 0, rem;
// store the number to the original number
int orgNum = n;
/* get the reverse of original number
store it in variable */
while (n != 0) {
remainder = n % 10;
revNum = revNum * 10 + rem;
n /= 10;
}
// check if reversed number and original number are equal
if (orgNum == revNum) {
System.out.println(orgNum + " is Palindrome.");
}
else {
System.out.println(orgNum + " is not Palindrome.");
}

Check endings of an String without built-in methods like endsWith() in Java

I want to check if every word in an string has specific endings with various length. I can't use arrays & methods for this like endsWith(). The only methods im allowed to use are charAt() and length().
public class TextAnalyse {
public static void main(String[] args) {
System.out.println(countEndings("This is a test", "t"));
System.out.println(countEndings("Waren sollen rollen", "en"));
System.out.println(countEndings("The ending is longer then every single word", "abcdefghijklmn"));
System.out.println(countEndings("Today is a good day", "xyz"));
System.out.println(countEndings("Thist is a test", "t"));
System.out.println(countEndings("This is a test!", "t"));
System.out.println(countEndings("Is this a test?", "t"));
}
public static int countEndings(String text, String ending) {
int counter = 0;
int counting;
int lastStringChar;
for (int i = 0; i < text.length(); i++) {
lastStringChar = 0;
if (!(text.charAt(i) >= 'A' && text.charAt(i) <= 'Z' || text.charAt(i) >= 'a' && text.charAt(i) <= 'z') || i == text.length() - 1) {
if( i == text.length() - 1 ){
lastStringChar = 1;
}
counting = 0;
for (int j = 0; j + lastStringChar < ending.length() && i > ending.length(); j++) {
if (text.charAt(i - ending.length() + j + lastStringChar) == ending.charAt(j)) {
counting = 1;
} else {
counting = 0;
}
}
counter += counting;
}
}
return counter;
}
}
The actual results are that I get one counting less, I guess its because it dont check the last chars properly.
The most simple solution I can come up with is the following:
Check, if a word ends with a given suffix:
public static boolean endsWith(String word, String suffix) {
if(suffix.length() > word.length()) {
return false;
}
int textIndex = (word.length() - 1);
int suffixIndex = (suffix.length() - 1);
while(suffixIndex >= 0) {
char textChar = word.charAt(textIndex);
char suffixChar = suffix.charAt(suffixIndex);
if(textChar != suffixChar) {
return false;
}
textIndex--;
suffixIndex--;
}
return true;
}
Split the given in its' words and use the above method to count every word ending with the given ending:
public static int countEndings(String text, String ending) {
{
//maybe remove punctuation here...
//(if yes, use String.replace for example)
}
String[] words = text.split(" ");
int counter = 0;
for(String word: words) {
if(endsWith(word, ending)) {
counter++;
}
}
return counter;
}
Also consider to remove unwanted punctuation, like '!' or '?' (...) - the above implementation will not recognize count any word ending with t in the String test!!
I guess you are able to use regular expression.
If you want count words with ending, you can use the following code:
public static int countEndings(String text, String ending) {
final Matcher wordWithEndMatches = Pattern.compile("\\b[A-Za-z]*" + ending + "\\b").matcher(text);
int count = 0;
while(wordWithEndMatches.find()) {
count++;
}
return count;
}

find subsequence in a string: Java

I have a string hackkkerrank and i have to find if any subsequence gives a result as hackerrank, if it is present then it gives result as YES otherwise NO.
Sample:
hereiamstackerrank: YES
hackerworld: NO
I don't know which String method should be applied, can anyone help me how to do it?
Here is my code:
static String hackerrankInString(String s) {
char str[] = {
'h','a','c','k','e','r','a','n','k'
};
while (s.length() >= 10) {
for (int i = 0; i < s.length(); i++) {
for (char c: str) {
if (s.indexOf(c)) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
}
Here is a built-in way, using regex:
String regex = "[^h]*+h[^a]*+a[^c]*+c[^k]*+k[^e]*+e[^r]*+r[^r]*+r[^a]*+a[^n]*+n[^k]*+k.*";
System.out.println("hereiamstackerrank".matches(regex) ? "YES" : "NO");
System.out.println("hackerworld".matches(regex) ? "YES" : "NO");
Output
YES
NO
You can make a generic method to check for subsequence like this:
public static boolean containsSubsequence(String subsequence, String text) {
StringBuilder buf = new StringBuilder();
for (int i = 0, j; i < subsequence.length(); i = j) {
j = subsequence.offsetByCodePoints(i, 1);
String ch = Pattern.quote(subsequence.substring(i, j));
buf.append("[^").append(ch).append("]*+").append(ch);
}
String regex = buf.append(".*").toString();
return text.matches(regex);
}
Test
System.out.println(containsSubsequence("hackerrank", "hereiamstackerrank") ? "YES" : "NO");
System.out.println(containsSubsequence("hackerrank", "hackerworld") ? "YES" : "NO");
Output
YES
NO
Of course, it is not very efficient, but it is one way to do it.
For a simpler and more efficient solution, that doesn't handle characters in the Supplement­ary Planes, you'd do this:
public static boolean containsSubsequence(String subsequence, String text) {
int j = 0;
for (int i = 0; i < text.length() && j < subsequence.length(); i++)
if (text.charAt(i) == subsequence.charAt(j))
j++;
return (j == subsequence.length());
}
Here is an old fashioned looping way, which increments the starting position of the second string based upon where the last char was found
String str1 = "hackerrank";
String str2 = "hereiamstackerrank";
int index = 0;
for (int i = 0; i < str1.length(); i++)
{
boolean notfound = true;
int x = index;
for (; x < str2.length(); x++) {
if (str1.charAt(i) == str2.charAt(x)) {
notfound = false;
break;
}
}
if (notfound) {
System.out.println("NO");
return;
}
index = x + 1;
}
System.out.println("YES");
An in-efficient alternative is
for (int i = 0; str1.length() > 0 && i < str2.length(); i++)
{
if (str1.charAt(0) == str2.charAt(i)) {
str1 = str1.substring(1);
}
}
System.out.println(str1.length() == 0 ? "YES" : "NO");
static String re="";
static String hackerrankInString(String s) {
String pattern="[^h]*+h[^a]*+a[^c]*+c[^k]*+k[^e]*+e[^r]*+r[^r]*+r[^a]*+a[^n]*+n[^k]*+k.*";
if(s.matches(pattern)){
re="YES";
}else{
re="NO";
}
return re;
}
There's no built in function in core libraries to check subsequence. There's one for substring but none for subsequence you're looking for.
You'll have to code it yourself.
Below is the pseudo code for this:
1. Traverse both original string and string under test.
2. Increment both's counter if characters are equal
3. Else increment originalString's counter only.
4. Repeat 2-3 `while` both strings are `not` empty.
5. Given string under test is subsequence if its counter is exhausted.

How to search via character matching with a skip distance?

As the title says, I'm working on a project in which I'm searching a given text, moby dick in this case, for a key word. However instead of the word being linear, we are trying to find it via a skip distance ( instead of cat, looking for c---a---t).
I've tried multiple ways, yet can't seem to get it to actually finish one skip distance, have it not work, and call the next allowed distance (incrementing by 1 until a preset limit is reached)
The following is the current method in which this search is done, perhaps this is just something silly that I'm missing?
private int[] search()
throws IOException
{
/*
tlength is the text file length,
plength is the length of the
pattern word (cat in the original post),
text[] is a character array of the text file.
*/
int i=0, j;
int match[] = new int[2];
int skipDist = 2;
while(skipDist <= 100)
{
while(i<=tlength-(plength * skipDist))
{
j=plength-1;
while(j>=0 && pattern[j]==text[i+(j * skipDist)])j--;
if (j<0)
{
match[0] = skipDist;
match[1] = i;
return match;
}
else
{
i++;
}
}
skipDist = skipDist + 1;
}
System.out.println("There was no match!");
System.exit(0);
return match;
}
I do not know about the method you posted, but you can use this instead. I've used string and char array for this:
public boolean checkString (String s)
{
char[] check = {'c','a','t'};
int skipDistance = 2;
for(int i = 0; i< (s.length() - (skipDistance*(check.length-1))); i++)
{
boolean checkValid = true;
for(int j = 0; j<check.length; j++)
{
if(!(s.charAt(i + (j*skipDistance))==check[j]))
{
checkValid = false;
}
}
if(checkValid)
return true;
}
return false;
}
Feed the pattern to match in the char array 'check'.
String "adecrayt" evaluates true. String "cat" evaluates false.
Hope this helps.
[This part was for fixed skip distance]
+++++++++++++++++++++++++++
Now for any skip distance between 2 and 100:
public boolean checkString (String s)
{
char[] check = {'c','a','t'};
int index = 0;
int[] arr = new int[check.length];
for(int i = 0; i< (s.length()); i++)
{
if(check[index]==s.charAt(i))
{
arr[index++] = i;
}
}
boolean flag = true;
if(index==(check.length))
{
for(int i = 0; i<arr.length-1; i++)
{
int skip = arr[i+1]-arr[i];
if(!((skip>2)&&(skip<100)))
{
flag = false;
}
else
{
System.out.println("Skip Distance : "+skip);
}
}
}
else
{
flag = false;
}
return flag;
}
If you pass in a String, you only need one line:
public static String search(String s, int skipDist) {
return s.replaceAll(".*(c.{2," + skipDist + "}a.{2," + skipDist + "}t)?.*", "$1");
}
If no match found, a blank will be returned.

Find the Number of Occurrences of a Substring in a String

Why is the following algorithm not halting for me?
In the code below, str is the string I am searching in, and findStr is the string occurrences of which I'm trying to find.
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while (lastIndex != -1) {
lastIndex = str.indexOf(findStr,lastIndex);
if( lastIndex != -1)
count++;
lastIndex += findStr.length();
}
System.out.println(count);
How about using StringUtils.countMatches from Apache Commons Lang?
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
System.out.println(StringUtils.countMatches(str, findStr));
That outputs:
3
Your lastIndex += findStr.length(); was placed outside the brackets, causing an infinite loop (when no occurence was found, lastIndex was always to findStr.length()).
Here is the fixed version :
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while (lastIndex != -1) {
lastIndex = str.indexOf(findStr, lastIndex);
if (lastIndex != -1) {
count++;
lastIndex += findStr.length();
}
}
System.out.println(count);
A shorter version. ;)
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
System.out.println(str.split(findStr, -1).length-1);
The last line was creating a problem. lastIndex would never be at -1, so there would be an infinite loop. This can be fixed by moving the last line of code into the if block.
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){
lastIndex = str.indexOf(findStr,lastIndex);
if(lastIndex != -1){
count ++;
lastIndex += findStr.length();
}
}
System.out.println(count);
Do you really have to handle the matching yourself ? Especially if all you need is the number of occurences, regular expressions are tidier :
String str = "helloslkhellodjladfjhello";
Pattern p = Pattern.compile("hello");
Matcher m = p.matcher(str);
int count = 0;
while (m.find()){
count +=1;
}
System.out.println(count);
I'm very surprised no one has mentioned this one liner. It's simple, concise and performs slightly better than str.split(target, -1).length-1
public static int count(String str, String target) {
return (str.length() - str.replace(target, "").length()) / target.length();
}
Here it is, wrapped up in a nice and reusable method:
public static int count(String text, String find) {
int index = 0, count = 0, length = find.length();
while( (index = text.indexOf(find, index)) != -1 ) {
index += length; count++;
}
return count;
}
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while((lastIndex = str.indexOf(findStr, lastIndex)) != -1) {
count++;
lastIndex += findStr.length() - 1;
}
System.out.println(count);
at the end of the loop count is 3; hope it helps
public int countOfOccurrences(String str, String subStr) {
return (str.length() - str.replaceAll(Pattern.quote(subStr), "").length()) / subStr.length();
}
A lot of the given answers fail on one or more of:
Patterns of arbitrary length
Overlapping matches (such as counting "232" in "23232" or "aa" in "aaa")
Regular expression meta-characters
Here's what I wrote:
static int countMatches(Pattern pattern, String string)
{
Matcher matcher = pattern.matcher(string);
int count = 0;
int pos = 0;
while (matcher.find(pos))
{
count++;
pos = matcher.start() + 1;
}
return count;
}
Example call:
Pattern pattern = Pattern.compile("232");
int count = countMatches(pattern, "23232"); // Returns 2
If you want a non-regular-expression search, just compile your pattern appropriately with the LITERAL flag:
Pattern pattern = Pattern.compile("1+1", Pattern.LITERAL);
int count = countMatches(pattern, "1+1+1"); // Returns 2
You can number of occurrences using inbuilt library function:
import org.springframework.util.StringUtils;
StringUtils.countOccurrencesOf(result, "R-")
Increment lastIndex whenever you look for next occurrence.
Otherwise it's always finding the first substring (at position 0).
The answer given as correct is no good for counting things like line returns and is far too verbose. Later answers are better but all can be achieved simply with
str.split(findStr).length
It does not drop trailing matches using the example in the question.
public int indexOf(int ch,
int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
So your lastindex value is always 0 and it always finds hello in the string.
try adding lastIndex+=findStr.length() to the end of your loop, otherwise you will end up in an endless loop because once you found the substring, you are trying to find it again and again from the same last position.
Try this one. It replaces all the matches with a -.
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int numberOfMatches = 0;
while (str.contains(findStr)){
str = str.replaceFirst(findStr, "-");
numberOfMatches++;
}
And if you don't want to destroy your str you can create a new string with the same content:
String str = "helloslkhellodjladfjhello";
String strDestroy = str;
String findStr = "hello";
int numberOfMatches = 0;
while (strDestroy.contains(findStr)){
strDestroy = strDestroy.replaceFirst(findStr, "-");
numberOfMatches++;
}
After executing this block these will be your values:
str = "helloslkhellodjladfjhello"
strDestroy = "-slk-djladfj-"
findStr = "hello"
numberOfMatches = 3
As #Mr_and_Mrs_D suggested:
String haystack = "hellolovelyworld";
String needle = "lo";
return haystack.split(Pattern.quote(needle), -1).length - 1;
Based on the existing answer(s) I'd like to add a "shorter" version without the if:
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int count = 0, lastIndex = 0;
while((lastIndex = str.indexOf(findStr, lastIndex)) != -1) {
lastIndex += findStr.length() - 1;
count++;
}
System.out.println(count); // output: 3
Here is the advanced version for counting how many times the token occurred in a user entered string:
public class StringIndexOf {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a sentence please: \n");
String string = scanner.nextLine();
int atIndex = 0;
int count = 0;
while (atIndex != -1)
{
atIndex = string.indexOf("hello", atIndex);
if(atIndex != -1)
{
count++;
atIndex += 5;
}
}
System.out.println(count);
}
}
This below method show how many time substring repeat on ur whole string. Hope use full to you:-
String searchPattern="aaa"; // search string
String str="aaaaaababaaaaaa"; // whole string
int searchLength = searchPattern.length();
int totalLength = str.length();
int k = 0;
for (int i = 0; i < totalLength - searchLength + 1; i++) {
String subStr = str.substring(i, searchLength + i);
if (subStr.equals(searchPattern)) {
k++;
}
}
This solution prints the total number of occurrence of a given substring throughout the string, also includes the cases where overlapping matches do exist.
class SubstringMatch{
public static void main(String []args){
//String str = "aaaaabaabdcaa";
//String sub = "aa";
//String str = "caaab";
//String sub = "aa";
String str="abababababaabb";
String sub = "bab";
int n = str.length();
int m = sub.length();
// index=-1 in case of no match, otherwise >=0(first match position)
int index=str.indexOf(sub), i=index+1, count=(index>=0)?1:0;
System.out.println(i+" "+index+" "+count);
// i will traverse up to only (m-n) position
while(index!=-1 && i<=(n-m)){
index=str.substring(i, n).indexOf(sub);
count=(index>=0)?count+1:count;
i=i+index+1;
System.out.println(i+" "+index);
}
System.out.println("count: "+count);
}
}
Matcher.results()
You can find the number of occurrences of a substring in a string using Java 9 method Matcher.results() with a single line of code.
It produces a Stream of MatchResult objects which correspond to captured substrings, and the only thing needed is to apply Stream.count() to obtain the number of elements in the stream.
public static long countOccurrences(String source, String find) {
return Pattern.compile(find) // Pattern
.matcher(source) // Mather
.results() // Stream<MatchResults>
.count();
}
main()
public static void main(String[] args) {
System.out.println(countOccurrences("helloslkhellodjladfjhello", "hello"));
}
Output:
3
here is the other solution without using regexp/patterns/matchers or even not using StringUtils.
String str = "helloslkhellodjladfjhelloarunkumarhelloasdhelloaruhelloasrhello";
String findStr = "hello";
int count =0;
int findStrLength = findStr.length();
for(int i=0;i<str.length();i++){
if(findStr.startsWith(Character.toString(str.charAt(i)))){
if(str.substring(i).length() >= findStrLength){
if(str.substring(i, i+findStrLength).equals(findStr)){
count++;
}
}
}
}
System.out.println(count);
If you need the index of each substring within the original string, you can do something with indexOf like this:
private static List<Integer> getAllIndexesOfSubstringInString(String fullString, String substring) {
int pointIndex = 0;
List<Integer> allOccurences = new ArrayList<Integer>();
while(fullPdfText.indexOf(substring,pointIndex) >= 0){
allOccurences.add(fullPdfText.indexOf(substring, pointIndex));
pointIndex = fullPdfText.indexOf(substring, pointIndex) + substring.length();
}
return allOccurences;
}
public static int getCountSubString(String str , String sub){
int n = 0, m = 0, counter = 0, counterSub = 0;
while(n < str.length()){
counter = 0;
m = 0;
while(m < sub.length() && str.charAt(n) == sub.charAt(m)){
counter++;
m++; n++;
}
if (counter == sub.length()){
counterSub++;
continue;
}
else if(counter > 0){
continue;
}
n++;
}
return counterSub;
}
🍑 Just a little more peachy answer
public int countOccurrences(String str, String sub) {
if (str == null || str.length() == 0 || sub == null || sub.length() == 0) return 0;
int count = 0;
int i = 0;
while ((i = str.indexOf(sub, i)) != -1) {
count++;
i += sub.length();
}
return count;
}
I was asked this question in an interview just now and I went completely blank. (Like always, I told myself that the moment the interview ends ill get the solution) which I did, 5 mins after the call ended :(
int subCounter=0;
int count =0;
for(int i=0; i<str.length(); i++) {
if((subCounter==0 && "a".equals(str.substring(i,i+1)))
|| (subCounter==1 && "b".equals(str.substring(i,i+1)))
|| (subCounter==2 && "c".equals(str.substring(i,i+1)))) {
++subCounter;
}
if(subCounter==3) {
count = count+1;
subCounter=0;
}
}
System.out.println(count);

Categories

Resources