I'm doing an online CPS course and a question requires me to write a code that counts the vowels(upper and lowercase) in a string. Here is my code:
public static int countVowels( String s )
{
{
if ( s.length() == 0 )
return 0 + countVowels(s);
else if ( (s.substring(0, 1) == "a" ) || (s.substring(0, 1) == "A") )
return 1 + countVowels(s.substring(1));
else if ( (s.substring(0, 1) == "e" ) || (s.substring(0, 1) == "E") )
return 1 + countVowels(s.substring(1));
else if ( (s.substring(0, 1) == "i" ) || (s.substring(0, 1) == "I") )
return 1 + countVowels(s.substring(1));
else if ( (s.substring(0, 1) == "o" ) || (s.substring(0, 1) == "O") )
return 1 + countVowels(s.substring(1));
else if ( (s.substring(0, 1) == "u" ) || (s.substring(0, 1) == "U") )
return 1 + countVowels(s.substring(1));
}
return countVowels(s.substring(1));
}
but I'm getting a "StackOverFlow" error and I'm not sure what to do. I know that the error means that the terminating condition isn't being reached. I'm not allowed to use anything that I haven't learned yet and I'm also not allowed to use for or while statements because this is a recursion problem.
Could I please get some help?
In the case when s.length() == 0 you are causing an infinite recursion. An empty string has 0 vowels, so you should edit 5th line to return 0; Another thing to watch out for: you're comparing strings with ==. This operator is intended for something else. Use equals instead. Take a look at this, for example: String comparison. That is s.substring(0, 1) == "a" should become s.substring(0, 1).equals("a")
As a matter of fact, there are some other pieces of advice I'd give you, like just storing the first letter in the string, instead of calculating it in every case (twice at that). Also, you can get the lower case character for the first character, so that you can reduce the cases you compare to twice. Also, add vowels to an array, this code is not DRY.
This is a possible solution in javascript. You can test it by creating a file 'something.html' and opening it in your browser.
<html>
<head></head>
<body>
<div id="input">
</div>
<div id='answer'>
</div>
<script>
var vowels = ['a','e','i','o','u'];
var testInput = 'Hello this is just a test. Out with it.';
function Contains(value, inArray) {
var found = false;
for(var j=0, size = inArray.length; j < size; j++) {
if(value.toLowerCase() === inArray[j]) {
found = true;
}
}
return found;
}
var vowelCounter = 0;
for(var i=0, j = testInput.length; i < j; i++) {
if(Contains(testInput[i], vowels)) {
vowelCounter +=1;
}
}
var inp = document.getElementById("input");
inp.innerHTML = 'Question <br/>' + testInput;
document.getElementById('answer').innerHTML = 'Number of Vowels: ' + vowelCounter;
</script>
</body>
</html>
I hope by now you would have completed your homework. I have solved the same problem in a shorter way:
public class CountVowels {
private static String vowels = "aeiou";
public static void main(String[] args){
String s = "RohanAskedAQuestion";
System.out.println(recursivelyCountVowels(s));
}
private static int recursivelyCountVowels(String s) {
if(s==null||s.length()==0)
{
return 0;
}
if(vowels.contains((CharSequence) s.substring(0, 1).toLowerCase())){
return 1+recursivelyCountVowels(s.substring(1));
}
return 0+recursivelyCountVowels(s.substring(1));
}
}
I hope it helps :) , I am also learning java so if anybody has any suggestion please do tell.
Thanks.
Maybe its a little late but still :)
public int recursiveCountVowels(String str,int count,int currentPosition)
{
str = str.toLowerCase();
if(str.trim().length() == 0)
return count;
if(currentPosition == str.length())
return count;
for(int i = currentPosition ; i < str.length();i++)
{
if(str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u')
count++;
currentPosition++;
}
return recursiveCountVowels(str, count, currentPosition);
}
vowel count (vc) - Return the number of vowels in an input string.
public static int vc(String s)
{
if(s.length() - 1 < 0) return 0;
return((("aeiou".indexOf((s.charAt(s.length()-1)+"").toLowerCase()) >= 0 ? 1 : 0))
+ vc((s = s.substring(0,s.length()-1))));
}
Related
I have recursive string that goes like this,
var1=[[1,2,3], [1,2,3]], var2=true, var3="hello", var4=(var1=[[1,2,3], [1,2,3]], var2=true, var3="hello")
I want to separate the string by commas and desired result is this,
var1=[[1,2,3], [1,2,3]]
var2=true
var3="hello"
var4=(var1=[[1,2,3], [1,2,3]], var2=true, var3="hello")
I have tried this regex, (([a-zA-Z0-9]*)=(.*),?\s?)*, to match the something like this, varx=(), but the complete string was matched.
I also tried to do this by traversing the string but was not able to separate strings like varx="...." because the quotes can contain anythings so there was no way to do this.
public static int fun2(int start_index, String str, int end_index) {
Stack<Character> charStack = new Stack<>();
charStack.add(str.charAt(start_index));
char opp = ' ';
if (str.charAt(start_index) == '(') {
opp = ')';
} else if (str.charAt(start_index) == '[') {
opp = ']';
} else if (str.charAt(start_index) == '[')
while (end_index < str.length() && !charStack.isEmpty()) {
if (str.charAt(end_index) == str.charAt(start_index)) {
charStack.add(str.charAt(start_index));
} else if (str.charAt(end_index) == opp) {
charStack.pop();
}
end_index++;
}
if (charStack.isEmpty()) {
System.out.println("correct");
System.out.println(str.substring(start_index, end_index));
}
return end_index;
// throw error
}
public static void fun(String str) {
int start = 0;
int end = -1;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '=') {
System.out.println("key = " + str.substring(start, end + 1));
start = i + 1;
end = start + 1;
if (str.charAt(start) == '[' || str.charAt(start) == '(' || str.charAt(i) == '"') {
System.out.println("value = ");
end = fun2(start, str, end);
start = end;
i = start;
}
} else if (str.charAt(i) == ',' || str.charAt(i) == ' ') {
start++;
end++;
} else {
end++;
}
}
}
Can anyone suggest any regex or piece of code that will do this for me. Thanks in advance.
To get the matches in the example data, you could match the key part without matching an equals sign.
For the value you can either match from an opening till closing parenthesis, or match until the next key part or end of string.
Note that this pattern does not takes any recursion from the parenthesis or square brackets into account. It depends on matching the parenthesis or using the comma as a separator.
[^\s=,]+=(?:\([^()]*\)|.+?)(?=,\s*[^\s=,]+=|$)
Regex demo
In Java with the doubled backslashes
String regex = "[^\\s=,]+=(?:\\([^()]*\\)|.+?)(?=,\\s*[^\\s=,]+=|$)";
I need to find the number of distinct vowels. I came up with the code below but it can't make distinction between same vowels:
public static int count_Vowels(String str) {
str = str.toLowerCase();
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u') {
count++;
}
}
return count;
}
I would start with five variables (one for each vowel) set to 0, iterate the characters in the input and set the corresponding variable to 1 if I find a match, and simply return the accumulated value of said variables. Like,
public static int count_Vowels(String str) {
int a = 0, e = 0, i = 0, o = 0, u = 0;
for (char ch : str.toLowerCase().toCharArray()) {
if (ch == 'a') {
a = 1;
} else if (ch == 'e') {
e = 1;
} else if (ch == 'i') {
i = 1;
} else if (ch == 'o') {
o = 1;
} else if (ch == 'u') {
u = 1;
}
}
return a + e + i + o + u;
}
You could use Set data structure and instead of incrementing the counter just add vowels to the set. At the end you can return just the size of the set.
The problem in your code is that you are not counting the distinct vowels, but all the vowels in the string. A Java-8 way to this:
public static int countDistinctVowels(String str) {
str = str.toLowerCase();
int count = (int) str.chars() // get IntStream of chars
.mapToObj(c -> (char) c) // cast to char
.filter(c -> "aeiou".indexOf(c) > -1) // remove all non-vowels
.distinct() // keep the distinct values
.count(); // count the values
return count;
}
Also use proper Java naming conventions: countDistinctVowels, no count_Distinct_Vowels.
there's definitely an issue here with this counting. at the very least. you should rethink this:
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u')
count++;
You could use the method contains
public static int count_Vowels(String str) {
str = str.toLowerCase();
int count = 0;
count += string.contains("a") ? 1 : 0;
count += string.contains("e") ? 1 : 0;
count += string.contains("i") ? 1 : 0;
count += string.contains("o") ? 1 : 0;
count += string.contains("u") ? 1 : 0;
return count;
}
I made explanations in the comments to the code:
public static int count_Vowels(String str) {
str = str.toLowerCase();
Set<Character> setOfUsedChars = new HashSet<>(); // Here you store used vowels
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u') { // if currently checked character is vowel...
setOfUsedChars.add(str.charAt(i)); // add this vowel to setOfUsedChars
}
}
return setOfUsedChars.size(); // size of this sets is a number of vowels present in input String
}
static void vow(String input){
String output=input.toLowerCase();
int flaga=0,flage=0,flagi=0,flago=0,flagu=0;
for(int i=0;i<input.length();i++) {
if((output.charAt(i))=='a' && flaga==0) {
System.out.print(input.charAt(i)+" ");
flaga++;
}
if(output.charAt(i)=='e' && flage==0) {
System.out.print(input.charAt(i)+" ");
flage++;
}
if(output.charAt(i)=='i' && flagi==0) {
System.out.print(input.charAt(i)+" ");
flagi++;
}
if(output.charAt(i)=='o' && flago==0) {
System.out.print(input.charAt(i)+" ");
flago++;
}
if(output.charAt(i)=='u' && flagu==0) {
System.out.print(input.charAt(i)+" ");
flagu++;
}
}
}
public static void main(String args[]) {
String sentence;
int v=0,c=0,ws=0;
Scanner sc= new Scanner(System.in);
sentence = sc.nextLine();
sc.close();
sentence.toLowerCase();
String res="";
for(int i=0;i<sentence.length();i++) {
if(sentence.charAt(i)=='a'||sentence.charAt(i)=='e'||sentence.charAt(i)=='i'||sentence.charAt(i)=='o'||sentence.charAt(i)=='u') {
if(res.indexOf(sentence.charAt(i))<0) {
res+=sentence.charAt(i);
v++;
}//System.out.println(res.indexOf(sentence.charAt(i)));
}
else if(sentence.charAt(i)==' ')
ws++;
else c++;
}
System.out.println(res);
System.out.println("no of vowels: "+v+"\n"+"no of consonants: "+c+"\n"+"no of
white spaces: "+ws);
}
You can use this Method to Find Count of Distinct vowels.
public static int count_Vowels(String str) {
char[] c = str.toLowerCase().toCharArray();
int Counter=0;
String NewString="";
for(int i=0;i<c.length;i++){
String tempString="";
tempString+=c[i];
if(!NewString.contains(tempString) && (c[i]=='a'||c[i]=='e'||c[i]=='i'||c[i]=='o'||c[i]=='u')){
Counter++;
NewString+=c[i];
}
}
return Counter;
}
Here is a solve for this problem without using objects. It's a crude but great solve for beginners who encounter this problem with limited js experience.
How to count unique vowels is a string;
function hasUniqueFourVowels(str){
let va = 0
let ve = 0
let vi = 0
let vo = 0
let vu = 0
let sum = 0
for(let i = 0; i < str.length; i++){
let char = str[i];
if(char === "i"){
vi = 1
}
if(char === "e"){
ve = 1
}
if(char === "a"){
va = 1
}
if(char === "o"){
vo = 1
}
if(char === "u"){
vu = 1
}
sum = va + vi + vo + ve + vu
if (sum >= 4){
return true
}
}
return false
}
#Test
public void numfindVoweles(){
String s="aeiouaedtesssiou";
char a[]=s.toCharArray();
HashMap<Character,Integer> hp= new HashMap<Character, Integer>();
for(char ch:a){
if(hp.containsKey(ch) && (ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')){
hp.put(ch,hp.get(ch)+1);
}
else if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u'){
hp.put(ch,1);
}
}
System.out.println(hp);
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
Found some interesting problem solving questions online and here it is.
You are to check the given String str if they contains matching parenthesis.
Example input: [ ] , [ ( ] ) , { [ ] } , { [ } ] , { [ } ) , { ] }
Example output: EQUAL, EQUAL, EQUAL, EQUAL, NOT EQUAL, NOT EQUAL
I have managed to complete the requirements for this feature using basics, just wondering if there is a better way of doing it?
String str = "{[(])}(){}";
int pairs = 0;
boolean unableToFind = false;
ArrayList<Character> anChar = new ArrayList<Character>();
for (int i = 0; i < str.length(); i++) {
anChar.add(str.charAt(i));
}
if (str.length() % 2 == 0) {
while (pairs != str.length() / 2) {
for (int i = 1; i < anChar.size(); i++) {
char a = (char) anChar.get(0);
char b = (char) anChar.get(i);
if (a == '{' && b == '}' || a == '[' && b == ']' || a == '(' && b == ')') {
anChar.remove(i);
anChar.remove(0);
pairs++;
break;
} else {
if (i == anChar.size() - 1) { // reached end of array
unableToFind = true;
break;
}
}
}
if (unableToFind)
break;
}
if (pairs == str.length() / 2) {
System.out.println("Log#01: The String have balanced parenthesis");
} else {
System.out.println("Log#02: The String do not have balanced parenthesis. (" + pairs + "/" + str.length() / 2 + " pairs found)");
}
} else {
System.out.println("Log#03: The String do not have even numbers of parenthesis");
}
Your approach is overly complex. All you need is three counters - countRound, countSquare, and countCurly. Initialize all three to zero, then walk the string character-by-character. If you see an opening parentheses, increment its counter; if it is a closing parentheses, decrement its corresponding counter. Once the loop is over, all three counters must be at zero; otherwise the numbers of parentheses do not match up.
Note: This does not check that parentheses are balanced, because your example does not require it (i.e. "[(])" produces "EQUAL" even through the input is unbalanced).
Just use a Stack. You need to go over each character in the String, and when you find a closing parenthesis, see if the top of the stack has the appropriate opening parenthesis. The logic would look something like this:
char c = input.charAt(i);
if(c == ')' || c == '}' || c == ']') {
if(stack.isEmpty())
return false;
Character stackTop = stack.pop();
if( (c == ')' && stackTop != '(') ||
(c == '}' && stackTop != '{') ||
(c == ']' && stackTop != '[') )
return false;
} else
stack.push(c);
For cases like "{{}", the stack will contain the first '{' at the end. So check to ensure if it's empty.
Not sure about the example you gave. If for "[ { ( ] } )", result is "EQUAL", when the string clearly isn't balanced, dasblinkenlight has the answer :)
Not as Elegant as the previous answers but it works.
Check if the count in for pair of brackets match.
public class EqualClass {
public static void main(String[] args) {
String input = "[ ] , [ ( ] ) , { [ ] } , { [ } ] , { [ } ) , { ] }";
String[] tokens = input.split(",");
char[] bracketTypes = { '[', '{', '(' };
char[] oppositeBracketType = { ']', '}', ')' };
for (String token : tokens) {
boolean equal = true;
char[] characters = token.toCharArray();
for (int indx = 0; indx < bracketTypes.length; indx++) {
if (EqualClass.Test(characters, bracketTypes[indx]) != EqualClass
.Test(characters, oppositeBracketType[indx])) {
equal = false;
break;
}
}
if (!equal) {
System.out.println(token + " Not Equal");
} else {
System.out.println(token + " Equal");
}
}
}
public static int Test(char[] tokenOfCharacter, char bracketType) {
int count = 0;
for (char character : tokenOfCharacter) {
if (character == bracketType) {
count += 1;
}
}
return count;
}
}
I am trying to figure out how to remove certain characters to make it English after it being in l33t speak. For example, I 54w 3 5hip5, would translate to I saw 3 ships. I need the 3 to stay a 3 here but in, N3v3r f0rg37 y0|_|r t0w31, I would need the 3's to become e's. Here is my code as follows. All the characters translate over correctly, but I just can't figure out how to do the 3's to e's.
My question is, what is needed to be added to get the 3's to be e's at a certain time, and to have my 3's stay 3's another time. Just so that you know, is that we aren't allowed to use regex, arrays, or string builder for this.
Rules are that if the number is supposed to be a number that it stays a number when you translate it from l33t to English, if the l33t number is a letter than you replace the number and turn it into the letter that corresponds to it.
I also have a different block of code that already takes into consideration the 3 to e's, but instead adds two u's instead of one.
Here are the replacements for the letters, a = 4, b = 8, e = 3, l = 1, o = 0, s = 5, t = 7, u = |_|, z = 2.
I decided to go the route of mike's answer since I understand exactly what's going on.
Thanks to everyone for the help!
Input/Output examples
This following code translates
I 54w 3 5hip5
to
I saw 3 ships
and
3 5hip5 4r3 c0ming m3 w4y
to
3 ships are coming me way
Code
public static String translateToEnglish(String phrase) {
if (phrase == null)
return null;
boolean threeAtBeginning = false, threeAtEnd = fal;
if (phrase.charAt(0) == '3' && phrase.charAt(1) == ' ')
threeAtBeginning = true;
int length = phrase.length();
if (phrase.charAt(length - 1) == '3' && phrase.charAt(length - 2) == ' ')
threeAtEnd = true;
String finished = phrase.replace('4', 'a') .replace('1', 'l') .replace('2', 'z') .replace('5', 's') .replace('8', 'b') .replace('0', 'o') .replace('7', 't') .replace("|_|", "u") .replace("3", "e");
finished = finished.replace(" e ", " 3 ");
if (threeAtBeginning)
finished = '3' + finished.substring(1);
if (threeAtEnd)
finished = finished.substring(0, length - 1) + '3';
return finished;
}
This is clearly homework, and the restrictions are clearly intended to prevent any sane solution, but here's an O(n^2) solution that seems to avoid the restrictions:
public class RemoveL33t {
public static void main(String[] args) {
System.out.println(removeL33t("I 54w 3 5hip5"));
System.out.println(removeL33t("I 54w 33 5hip5"));
System.out.println(removeL33t("I 54w 45 5hip5"));
System.out.println(removeL33t("N3v3r f0rg37 y0|_|r t0w31"));
}
public static String removeL33t(String s) {
String result = "";
for (int pos = 0;;) {
// Find the beginning of the next word.
int whitespaceBegin = pos;
while (pos < s.length() && Character.isWhitespace(s.charAt(pos))) {
pos++;
}
// Add the whitespace to the result.
result += s.substring(whitespaceBegin, pos);
// If there is no next word, then we're done.
if (pos >= s.length()) {
return result;
}
// Find the end of the word. Determine if the word is entirely numbers.
int wordBegin = pos;
boolean nonNumber = false;
while (pos < s.length() && !Character.isWhitespace(s.charAt(pos))) {
nonNumber |= s.charAt(pos) < '0' || s.charAt(pos) > '9';
pos++;
}
// Append the word. Perform replacements if it contains a non-number.
if (nonNumber) {
result += s.substring(wordBegin, pos)
.replace('4', 'a')
.replace('8', 'b')
.replace('3', 'e')
.replace('1', 'l')
.replace('0', 'o')
.replace('5', 's')
.replace('7', 't')
.replace("|_|", "u")
.replace('2', 'z');
} else {
result += s.substring(wordBegin, pos);
}
}
}
}
I think this is it.
public static String translateToEnglish(String phrase) {
if (phrase == null) {
return null;
}
String finished = phrase.replace('4', 'a') .replace('1', 'l') .replace('2', 'z') .replace('5', 's') .replace('8', 'b') .replace('0', 'o') .replace('7', 't') .replace("|_|", "u") .replace("3", "e");
finished = finished.replace(" e ", " 3 ");
if(finished.startsWith("e ")){
finished = "3 " + finished.substring(2);
}
if(finished.endsWith(" e")){
finished = finished.substring(0, finished.length()-2) + " 3";
}
return finished;
}
I don't know if this is the answer, but is the best i could think of
public static void main (String[] args) throws java.lang.Exception
{
String c = "I 54w 45 5hip5";
for(String s: c.split(" ")){
try{
Integer.parseInt(s);
System.out.print(s + " ");
}
catch(NumberFormatException e){
s = s.replace('4', 'a').replace('1', 'l').replace('2', 'z').replace('5', 's').replace('8', 'b').replace('0', 'o').replace('7', 't').replace("|_|", "u").replace("3", "e");
System.out.print(s + " ");
}
}
}
This is for your "new" code that you decided to use, or this could just be an alternate solution. The input/output is identical to the samples I gave in my other answer:
public static String translateToEnglish(String phrase) {
if (phrase == null)
return null;
String finished = "";
for (int i = 0; i < phrase.length(); i++) {
char c = phrase.charAt(i);
if (c == '4')
finished += 'a';
else if (c == '3') {
if (i != phrase.length() - 1)
{
if (phrase.charAt(i + 1) == ' ') {
if (i == 0)
finished += c;
else
if (phrase.charAt(i - 1) == ' ')
finished += c;
else
finished += 'e';
}
else
finished += 'e';
}
else
{
if (phrase.charAt(i - 1) == ' ')
finished += c;
else
finished += 'e';
}
} else if (c == '1')
finished += 'l';
else if (c == '2')
finished += 'z';
else if (c == '5')
finished += 's';
else if (c == '7')
finished +='t';
else if (c == '8')
finished += 'b';
else if (c == '0')
finished += 'o';
else if (i + 2 < phrase.length() && phrase.charAt(i + 1) == '_' && phrase.charAt(i + 2) == '|') {
finished += 'u';
i += 2;
} else
finished += c;
}
return finished;
}
I have the following function.
private boolean codeContains(String name, String code) {
if (name == null || code == null) {
return false;
}
Pattern pattern = Pattern.compile("\\b" + Pattern.quote(name) + "\\b");
Matcher matcher = pattern.matcher(code);
return matcher.find();
}
It is called many thousand times in my code, and is the function in which my program spends the most amount of time in. Is there any way to make this function go faster, or is it already as fast as it can be?
If you don't need to check word boundaries, you might do this :
private boolean codeContains(String name, String code) {
return name != null && code != null && code.indexOf(name)>=0;
}
If you need to check word boundaries but, as I suppose is your case, you have a big code in which you often search, you could "compile" the code once by
splitting the code string using the split method
putting the tokens in a HashSet (checking if a token is in a hashset is reasonably fast).
Of course, if you have more than one code, it's easy to store them in a structure adapted to your program, for example in a map having as key the file name.
"Plain" string operations will (almost) always be faster than regex, especially when you can't pre-compile the pattern.
Something like this would be considerably faster (with large enough name and code strings), assuming Character.isLetterOrDigit(...) suits your needs:
private boolean codeContains(String name, String code) {
if (name == null || code == null || code.length() < name.length()) {
return false;
}
if (code.equals(name)) {
return true;
}
int index = code.indexOf(name);
int nameLength = name.length();
if (index < 0) {
return false;
}
if (index == 0) {
// found at the start
char after = code.charAt(index + nameLength);
return !Character.isLetterOrDigit(after);
}
else if (index + nameLength == code.length()) {
// found at the end
char before = code.charAt(index - 1);
return !Character.isLetterOrDigit(before);
}
else {
// somewhere inside
char before = code.charAt(index - 1);
char after = code.charAt(index + nameLength);
return !Character.isLetterOrDigit(after) && !Character.isLetterOrDigit(before);
}
}
And a small test succeeds:
#Test
public void testCodeContainsFaster() {
final String code = "FOO some MU code BAR";
org.junit.Assert.assertTrue(codeContains("FOO", code));
org.junit.Assert.assertTrue(codeContains("MU", code));
org.junit.Assert.assertTrue(codeContains("BAR", code));
org.junit.Assert.assertTrue(codeContains(code, code));
org.junit.Assert.assertFalse(codeContains("FO", code));
org.junit.Assert.assertFalse(codeContains("BA", code));
org.junit.Assert.assertFalse(codeContains(code + "!", code));
}
This code seemed to do it:
private boolean codeContains(String name, String code) {
if (name == null || code == null || name.length() == 0 || code.length() == 0) {
return false;
}
int nameLength = name.length();
int lastIndex = code.length() - nameLength;
if (lastIndex < 0) {
return false;
}
for (int curr = 0; curr < lastIndex; ) {
int index = code.indexOf(name, curr);
int indexEnd = index + nameLength;
if (index < 0 || lastIndex < index) {
break;
}
boolean leftOk = index == curr ||
index > curr && !Character.isAlphabetic(code.charAt(index - 1));
boolean rightOk = index == lastIndex ||
index < lastIndex && !Character.isAlphabetic(code.charAt(indexEnd));
if (leftOk && rightOk) {
return true;
}
curr += indexEnd;
}
return false;
}
The accepted answer goes to dystroy as he was the first to point me in the right direction, excellent answer by Bart Kiers though, +1!