Replace entry in String Array - java

I have a String Array with multiple entries in it. I want to transcribe this String Array into another one, replacing specific entries with a digit (k in this case).
What I've tried so far:
public void replace(String[] eqh, char var, int maxX){
String[] holder = new String[eqh.length];
String comp = "";
for (int k = -maxX/2; k <= maxX/2; k++){
for (int i = 0; i< eqh.length; i++){
if (eqh[i].equals(var)){
holder[i] = ""+k;
} else {
holder[i] = eqh[i];
}
comp = Arrays.toString(holder);
System.out.println("comp: "+comp);
}
/// some stuff with comp here
}
Unfourtunatley this is not working, the return for comp is exactly the same as the input from eqh.

You are comparing strings with chars in eqh[i].equals(var) (it will always return false). If you want to check whether first char is equals to var, do eqh[i].charAt(0) == var
Also, it is not a good practice to convert integers to strings doing ""+k. Use Integer.toString(k) or String.valueOf(k).

You are trying to check if a String is equals to a char, the result of this test will always be false.
You can use eqh[i].indexOf(var) >= 0 to test if a String contains a char.

Related

How to check if a String can be formed from the characters of another String in Java?

A string is good if it can be formed by characters from chars. I want to return the sum of lengths of all good strings in words.
Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation:
The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.
Below is the code that I have written.
class Solution
{
public int countCharacters(String[] words, String chars)
{
int k = 0, count = 0;
Set<Character> set = new HashSet<>();
for(int i = 0; i < chars.length(); i++)
{
set.add(chars.charAt(i));
}
StringBuilder chrs = new StringBuilder();
for(Character ch : set)
{
chrs.append(ch);
}
for(int i = 0; i < words.length; i++)
{
char[] ch = words[i].toCharArray();
for(int j = 0; j < ch.length; j++)
{
if(chrs.contains("" + ch[j]))
{
k++;
}
}
if(k == words[i].length())
{
count+= k;
}
}
return count;
}
}
Output:
Line 24: error: cannot find symbol
if(chrs.contains("" + ch[j]))
Can someone help me? What am I doing wrong in accessing the character?
The issues which I noticed is you are using contains() to compare a String and a character. But the contains() method is a Java method to check if String contains another substring or not.
So you can solve this by converting the character to a string.
Ex 1:
if(chars.contains(Character.toString(ch[j]))){
k++;
} else {
}
Ex 2:
f(chars.contains(""+ch[j]))
{
k++;
} else {
}
Otherwise, You can compare if the string contains a char by using indexOf(). If the string isn't containing the char it return -1. Please refer bellow example.
Ex:
if(chars.indexOf(ch[j])!=-1){
k++;
} else {
}
contains tells you if a string is contained in another string. But in your case ch[j] is not a string but a char, so you can't use contains.
Instead, use indexOf, it returns -1 if the char is not present in the string.
the most simple way is
chars.contains("" + ch[i]);
Here, ch[j] is not a string but a char, so you can't use contains as you've done. Instead, make the following change.
chars.contains(String.valueOf(ch[j]));

Comparing string character by character in Java

How to compare individual character that is stored in a variable in Java?
String value = "abaabb";
Now how can I know that abaabb consist of only a and b in it and no other characters like c, d, ...
For this I want a way to compare individual characters in abaabb.
You can use .charAt() method:
String x="aabbbb";
for (int i = 0; i < x.length(); i++) {
if(x.charAt(i)=='a' || x.charAt(i)=='b') {
System.out.println("a or b");
}
}
You could use String#matches with Regular Expression:
boolean valid = "abaabb".matches("[ab]+");
easiest solution:
String value = "abaabb";
Set<Character> letters = new HashSet<Character>();
for(int i = 0; i < value.length(); i++){
letters.add(value.charAt(i));
}
//Edit
#Trincot
In set we collect unique characters in string, then we can build second collection with letters to check if only 'a' and 'b' are present
Set<Character> check = new HashSet<>();
check.add('a');
check.add('b');
letters.removeAll(check);
System.out.println(letters.isEmpty());

Java: Determining if a word contains letters that can be found in another word?

For example:
If you have a String "magikarp", and you tested it against "karma", this would be true, because all of the letters that make up "karma" can be found in "magikarp".
"kipp" would return false, because there is only one "p" in "magikarp."
This is the attempt that I have right now, but I don't think it's very efficient, and it doesn't return correctly for cases when there are multiple occurrences of one letter.
private boolean containsHelper(String word, String word2){
for (int i = 0; i < word2.length(); i ++){
if (!word.contains(String.valueOf(word2.charAt(i)))){
return false;
}
}
return true;
}
I don't write the program here, but let you know how to do. There are 2 ways to do this considering complexity:
1) If you are sure that you would be getting only a-z/A-Z characters in the string, then take a array of size 26. Loop thorough the first string and place the count of the character appeared in the respective index. Say for example you have String "aabcc". Now array would look like [2,1,2,0,...0]. Now loop through the second String, and at each character, subtract the 1 from the array at the respective character position and check the resultant value. If value is less than 0, then return false. For example you have "aacd". When you are at d, you would be doing (0-1), resulting -1 which is less than 0, hence return false.
2) Sort the characters in the each String, and then compare.
Since you are only checking for characters, it would be more efficient to use indexOf and to check if it return -1 as contains itself call indexOf but with some other trims...
However, I think it would be simplier to convert the String to an array of char and to remove them if they are found which would also handle the case of multiple occurences.
So you're algorithm woud look something like this :
private final boolean containsHelper(final String word, final String word2)
{
char[] secondWordAsCharArray = word2.toCharArray();
char[] firstWordAsCharArray = word.toCharArray();
Arrays.sort(firstWordAsCharArray);//Make sure to sort so we can use binary search.
int index = 0;
for(int i = 0; i++ < secondWordAsCharArray.length;)
{
index = Arrays.binarySearch(firstWordAsCharArray, secondWordAsCharArray[i]);//Binary search is a very performant search algorithm
if(index == -1)
return false;
else
firstWordAsCharArray[index] = ''; //A SENTINEL value, set the char a value you are sure that will never be in word2.
}
}
Basically, what I do is :
Convert both word to char array to make it easier.
Sort the char array of the word we inspect so we can use binary search.
Loop over all characters of the second word.
retrieve the index using the binary search algorithm (a very performant algorithm on char, the best from my knowledge).
if index is -1, it was not found so we can return false.
else make sure we unset the character.
You need to ensure that for any character c that appears in the second string, the number of times that c appears in the second string is no greater than the number of times that c appears in the first string.
One efficient way to tackle this is to use a hashmap to store the count of the characters of the first string, and then loop through the characters in the second string to check whether their total count is no greater than that in the first string. The time and space complexity are O(n) in the worst case, where n is the length of the input strings.
Here is the sample code for your reference:
import java.util.HashMap;
import java.util.Map;
public class HashExample {
public static void main(String[] args) {
System.out.println(containsHelper("magikarp", "karma")); // true
System.out.println(containsHelper("magikarp", "kipp")); // false
}
private static boolean containsHelper(String word, String word2) {
Map<Character, Integer> hm = new HashMap<>();
for (int i = 0; i < word.length(); i++) {
Character key = word.charAt(i);
int count = 0;
if (hm.containsKey(key)) {
count = hm.get(key);
}
hm.put(key, ++count);
}
for (int i = 0; i < word2.length(); i++) {
Character key = word2.charAt(i);
if (hm.containsKey(key)) {
int count = hm.get(key);
if (count > 0) {
hm.put(key, --count);
} else {
return false;
}
} else {
return false;
}
}
return true;
}
}
On possible algorithm is to remove all letters from your second word that don't occur in the first, sort both and then compare them.
Here is a reasonable way to achieve that in Java 8:
List<Integer> wordChars = word.chars().sorted().collect(Collectors.toList());
List<Integer> searchChars = search.chars()
.filter(wordChars::contains).sorted().collect(Collectors.toList());
return wordChars.equals(searchChars);

Function to match array of char to a string

I am trying to implement a function to compare between a 5 letters string and an array of char and to match them by comparing every char of the string to every char of the array
when I try to use it, it always returns something like [C#bebf1eb
Here's my function:
static String matching(String myWord1, char[] word_taken) {
char result[] = new char[5];
int k = 0;
char[] myWord = myWord1.toCharArray();
for (int i = 0; i < myWord.length; i++) {
for (int j = 0; j < word_taken.length; j++) {
if (myWord[i] == word_taken[j]) {
result[k] = myWord[i];
k++;
break;
}
}
}
return result.toString();
}
when I try to use it, it always returns something like [C#bebf1eb
Yes the toString() method for arrays is not overidden so you get the default implementation.
Use the String constructor that takes a char array instead.
return new String(result);
If you want to avoid to recopy the content of the array when creating your String, you could use a StringBuilder and append the char to it when it's needed.
At the end, simply return myStringBuilder.toString();
Yes I have also face the same problem and get the correct result by creating a string object
return new String(result);

Checking to see whether a string has certain characters in alphabetical order

I have to check a word/phrase and say whether the vowels in it are in alphabetical or reverse alphabetical order.
Im so close to getting it. Its just the final bit comparing the numbers in the array, to see whether or not they are in descending order etc. I know I have to make a nested for loop but Im not sure exactly how to do it. Thanks for the help.
public static void main(String [] args)
{
String result = "", result2="";
String userInput = "aeiou";
int [] array = new int[userInput.length()];
for(int i = 0; i < string.length(); ++i)
{
char c = replace.charAt( i );
int j = (int) c;
array[i] = j;
//printing unicode symbols (only for testing)
result2 += array[i] +",";
System.out.println(j);
}
boolean sequence = false;
for(int i = 0; i <array.length-1 && !sequence; i++)
{
for(int x =i+1; x<array.length; x++)
{
//Here I am checking to see whether or not they are in alphabetical order
if(array[i] < array[x])
sequence = true;
if(sequence == true)
result = "The vowels are in alphabetical order";
else
result = "The vowels are not in alphabetical order";
}
}
System.out.println(result);
}
Since you are using replaceAll(), I assume you can also use matches() (replace is the variable that contains the string after you replace everything but the vowels):
boolean isAscending = replace.matches("a*e*i*o*u*");
boolean isDescending = replace.matches("u*o*i*e*a*");
Well, there are some special cases here that doesn't seem to be considered in your code:
String in replace variable is empty (no vowel)
Only contains one vowel being repeated (e.g. pool --> oo)
In both cases above, isAscending and isDescending will both be true.
try
String input = "abc";
char[] a = input.toCharArray();
Arrays.sort(a);
StringBuilder sb = new StringBuilder();
sb.append(a);
if (input.equals(sb.toString())) {
System.out.println("ascending");
} else if (input.equals(sb.reverse().toString())) {
System.out.println("descending");
} else {
System.out.println("unsorted");
}

Categories

Resources