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);
Related
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]));
I am attempting to solve a problem where I create a method that counts the number of occurrences of capital and lowercase ("A" or "a") in a certain string. I have been working on this problem for a week now, and the main error that I am receiving is that "char cannot be dereferenced". Can anyone point me in the correct direction on this Java problem? Thank you.
class Main{
public static int countA (String s)
{
String s1 = "a";
String s2 = "A";
int count = 0;
for (int i = 0; i < s.length; i++){
String s3 = s.charAt(i);
if (s3.equals(s1) || s3.equals(s2)){
count += 1;
}
else{
System.out.print("");
}
}
}
//test case below (dont change):
public static void main(String[] args){
System.out.println(countA("aaA")); //3
System.out.println(countA("aaBBdf8k3AAadnklA")); //6
}
}
try a simpler solution
String in = "aaBBdf8k3AAadnklA";
String out = in.replace ("A", "").replace ("a", "");
int lenDiff = in.length () - out.length ();
Also as #chris mentions in his answer, the String could be converted to lowercase first and then only do a single check
the main error that I am receiving is that "char cannot be
dereferenced"
change this:
s.length // this syntax is incorrect
to this:
s.length() // this is how you invoke the length method on a string
also, change this:
String s3 = s.charAt(i); // you cannot assign a char type to string type
to this:
String s3 = Character.toString(s.charAt(i)); // convert the char to string
another solution to accomplishing your task in a simpler manner is by using the Stream#filter method. Then convert each String within the Stream to lowercase prior to comparison, if any Strings match "a" we keep it, if not we ignore it and at the end, we simply return the count.
public static int countA(String input)
{
return (int)Arrays.stream(input.split("")).filter(s -> s.toLowerCase().equals("a")).count();
}
For counting the number of time 'a' or 'A' appears in a String:
public int numberOfA(String s) {
s = s.toLowerCase();
int sum = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == 'a')
sum++;
}
return sum;
}
Or just replace everything else and see how long your string is:
int numberOfA = string.replaceAll("[^aA]", "").length();
To find the number of times character a and A appear in string.
int numA = string.replaceAll("[^aA]","").length();
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.
Could smb please explaing the process of sorting characters of String alphabetically? For example, if I have String "hello" the output should be "ehllo" but my code is doing it wrong.
public static void main(String[] args)
{
String result = "";
Scanner kbd = new Scanner(System.in);
String input = kbd.nextLine();
for(int i = 1; i < input.length(); i++)
{
if(input.charAt(i-1) < input.charAt(i))
result += input.charAt(i-1);
//else
// result += input.charAt(i);
}
System.out.println(result);
}
}
You may do the following thing -
1. Convert your String to char[] array.
2. Using Arrays.sort() sort your char array
Code snippet:
String input = "hello";
char[] charArray = input.toCharArray();
Arrays.sort(charArray);
String sortedString = new String(charArray);
System.out.println(sortedString);
Or if you want to sort the array using for loop (for learning purpose) you may use (But I think the first one is best option ) the following code snippet-
input="hello";
char[] charArray = input.toCharArray();
length = charArray.length();
for(int i=0;i<length;i++){
for(int j=i+1;j<length;j++){
if (charArray[j] < charArray[i]) {
char temp = charArray[i];
charArray[i]=arr[j];
charArray[j]=temp;
}
}
}
You can sort a String in Java 8 using Stream as below:
String sortedString =
Stream.of("hello".split(""))
.sorted()
.collect(Collectors.joining());
Procedure :
At first convert the string to char array
Then sort the array of character
Convert the character array to string
Print the string
Code snippet:
String input = "world";
char[] arr = input.toCharArray();
Arrays.sort(arr);
String sorted = new String(arr);
System.out.println(sorted);
Sorting as a task has a lower bound of O(n*logn), with n being the number of elements to sort. What this means is that if you are using a single loop with simple operations, it will not be guaranteed to sort correctly.
A key element in sorting is deciding what you are sorting by. In this case its alphabetically, which, if you convert each character to a char, equates to sorting in ascending order, since a char is actually just a number that the machine maps to the character, with 'a' < 'b'. The only gotcha to look out for is mixed case, since 'z' < 'A'. To get around, this, you can use str.tolower(). I'd recommend you look up some basic sorting algorithms too.
Your for loop is starting at 1 and it should be starting at zero:
for(int i = 0; i < input.length(); i++){...}
You can do this using Arrays.sort, if you put the characters into an array first.
Character[] chars = new Character[str.length()];
for (int i = 0; i < chars.length; i++)
chars[i] = str.charAt(i);
// sort the array
Arrays.sort(chars, new Comparator<Character>() {
public int compare(Character c1, Character c2) {
int cmp = Character.compare(
Character.toLowerCase(c1.charValue()),
Character.toLowerCase(c2.charValue())
);
if (cmp != 0) return cmp;
return Character.compare(c1.charValue(), c2.charValue());
}
});
Now build a string from it using StringBuilder.
Most basic and brute force approach using the two for loop:
It sort the string but with the cost of O(n^2) time complexity.
public void stringSort(String str){
char[] token = str.toCharArray();
for(int i = 0; i<token.length; i++){
for(int j = i+1; j<token.length; j++){
if(token[i] > token[j]){
char temp = token[i];
token[i] = token[j];
token[j] = temp;
}
}
}
System.out.print(Arrays.toString(token));
}
public class SortCharcterInString {
public static void main(String[] args) {
String str = "Hello World";
char[] arr;
List<Character> L = new ArrayList<Character>();
for (int i = 0; i < str.length(); i++) {
arr = str.toLowerCase().toCharArray();
L.add(arr[i]);
}
Collections.sort(L);
str = L.toString();
str = str.replaceAll("\\[", "").replaceAll("\\]", "")
.replaceAll("[,]", "").replaceAll(" ", "");
System.out.println(str);
}
I have a String entered by the User.
I'm trying to replace all non-uppercase letters(i.e. numbers, or symbols) with spaces without using methods such as replace(), Stringbuilders, or arrays.
This is what I have so far :
public static void formatPlaintext(String sentence){
String sentenceUpper = sentence.toUpperCase();
System.out.println(sentenceUpper);
String emptyString = " ";
for(int i = 0; i< sentenceUpper.length() ; i++){
char ch = sentenceUpper.charAt(i);
if(ch < 'A' || ch > 'Z'){
ch = emptyString.charAt(0);
}
}
}//end of formatPlaintext
I keep getting the error that String index is out of range. I believe it has to do with :
ch = emptyString.charAt(0);
because emptyString doesn't have any characters. But even if I put an arbitrary constant in, it doesn't replace the non-letters with this arbitrary constant.
This isn't how you replace characters in a Java string. In Java, strings are immutable, so you can't set any given index. Additionally, the charAt() method doesn't and can't do anything to the string you're calling it on - all it does is just return the char at that position. Lastly, you probably shouldn't be using void - return the String with characters replaced at the end of the method, then use the return value. You can accomplish this by iterating through your initial string and build a new string, using the static isUpperCase method of the Character class:
public static String formatPlainText(String sentence)
{
String replacedSentence = "";
for(int i = 0; i< sentence.length() ; i++){
char ch = sentence.charAt(i);
if (Character.isUpperCase(ch)) {
replacedSentence += ch;
}
else {
replacedSentence += " ";
}
}
return replacedSentence;
}
If you're going to be using this frequently, or for particularly long Strings, you should absolutely use a StringBuilder instead - concatenating String on a character-by-character basis is deeply inefficient.
You have to remember that arguments in Java are passed as values, not as references, and in this case the String is an immutable object, i.e. an String cannot be changed, when you do a concatenation or replace you're effectively creating a new String.
What I would recommend is to modify your code a little bit to return the new String that was built.
public static String formatPlaintext(String sentence){
String sentenceUpper = sentence.toUpperCase();
System.out.println(sentenceUpper);
StringBuilder builder = new StringBuilder;
for(int i = 0; i< sentenceUpper.length() ; i++){
char ch = sentenceUpper.charAt(i);
if(ch < 'A' || ch > 'Z'){
builder.append(' ');
} else {
builder.append(ch);
}
}
return builder.toString();
}