Finding Letters in a String and comparing Chars (Java) - java

I'm trying to make a basic program where it checks if a word is a palindrome, and I need to figure out how to do two things.
How do I figure out how many letters are in a string?
and
How do I compare two chars to see if they are the same?
Thanks in adv.

How do I figure out how many letters are in a string?
String in Java is immutable object which means it does not change. So the following code creates new string every time it is needed:
String s = "Hello";
s += " World";
After above introduction the answer to question nr 1 is
int len = s.length();
How do I compare two chars to see if they are the same?
String has access method for its characters, that you can use to access and compare them:
char one = s.charAt(0);
char two = s.charAt(1);
if (one == two) {
:
}
For your assignment I would recommend to use public char[] toCharArray() method and loop the array for accessing each character.

1.) StringName.length() <- Java has a method that will return the length of the string
2.) charName == charName2 <- primitive type can use the comparison operator
You have some good ideas that will help you write a palindrome program. I will offer no hints though so you can figure it out. good luck. <-Taken (bad guy) voice

Related

How do you find the alphabetically last letter of a string using recursion (no loops!) and without using arrays in Java?

Got something for you all.
As the title of the problem suggests, I am trying to implement a non-array, non-looping, recursive method to find the alphabetically last letter in a string.
I think that I understand the nature of the problem I'm trying to solve, but I don't know how to start with the base case and then the recursion.
Can anyone be willing to solve this problem?
In this case, I would like the following code:
//Method Definition
public static String findZenithLetter(String str) {
//Put actual working Java code that finds the alphabetically last letter of the desired string here.
//Use recursion, not loops! :)
//Don't use arrays! ;)
}
//Driver Code
System.out.println(findZenithLetter("I can reach the apex, at the top of the world."));
//Should print the String "x" if implemented properly
I have tried to attempt numerous, but currently failed ways of solving this problem, including but not limited to:
Sorting the string by alphabetical order then finding the last letter of the new string, excluding punctuation marks.
Using the compareTo() method to compare two letters of the string side by side, but that has yet to work as I am so tempted to use loops, not recursion. I need a recursive method to solve this, though. :)
In the end, the best piece of code that I've written for this problem was just a drawn-out way to compute just the last character of a string and not actually THE alphabetically last character.
This is quite simple. All you need is just iterate (in the recursion of course), and check all characters int he string with local maximum.
public static char findZenithLetter(String str) {
return findZenithLetter(str, 0, 'a');
}
private static char findZenithLetter(String str, int i, char maxCh) {
if (i >= str.length())
return maxCh;
char ch = Character.toLowerCase(str.charAt(i));
if (Character.isLetter(ch))
maxCh = ch > maxCh ? ch : maxCh;
return findZenithLetter(str, i + 1, maxCh);
}
Nibble off the first character at each recursion, returning the greater of it and the greatest found in the rest of the input:
public static String findZenithLetter(String str) {
if (str.isEmpty()) {
return ""; // what's returned if no letters found
}
String next = str.substring(0, 1);
String rest = findZenithLetter(str.substring(1));
return Character.isLetter(next.charAt(0)) && next.compareToIgnoreCase(rest) > 0 ? next : rest;
}
See live demo.
The check for Character.isLetter() prevents non-letter characters, which may be "greater than" letters being returned.
If no letters are found, a blank is returned.

How to compare characters in two different strings

Lets say i have "jfk" and "jfc". I want to iterate through both strings and find out if and where they differ. I am trying to see if the strings are anagrams. "new door" and "one word" are anagrams. If its not an anagram i want the code to tell me by how many characters the strings differ. The jfk and jfc differ by 1. "macd" and "mebc" differ by 2 and they cant be anagrams. If the two strings are different lengths then they can't be anagrams.
I tried iterating through the strings but that's when i got stuck. I have no idea how to iterate through both strings at the same time and find out how if they differ by certain characters or not. I only got as far as checking if both strings were the same length.
static void isAnagram(List <String> s1, List <String> s2) {
if (s1.length() != s2.length()) {
System.out.println("Not anagrams");
} else {
for(int i = 0; i < s1.length(); i++) {
for(int j = 0; j < s2.lenth(); j++) {//i know that iterating through both strings like this does not make sense but i am stuck.
}```
Convert the arrays to char arrays. Then sort the arrays alphabetically after that compare them character by character.
String str = "abc";
char[] chars = str.toCharArray();
you can use this to convert string to char array,next it will be very easy loop the char array by running a simple if condition and increment a variable which will tell the difference of words.
If you are allowed additional libraries, you should have a look at Google’s Guava, espacially at com.google.common.collect.Multiset<E> and it’s implementations. You can put the characters of each string into an Multiset<Character> (not a Multiset, that will not work, as E must be a reference type, no primitive). Both strings are anagrams if multiset1.equals(multiset2).
Of both for loops, it seems to me that you only need one of the loop and use the same counter for both strings?

How to delete duplicated characters in a string?

Okay, I'm a huge newbie in the world of java and I can't seem to get this program right. I am suppose to delete the duplicated characters in a 2 worded string and printing the non duplicated characters.
for example:I input the words "computer program." the output should be "cute" because these are the only char's that are not repeated.
I made it until here:
public static void main(String[] args) {
System.out.print("Input two words: ");
String str1 = Keyboard.readString();
String words[] = str1.split(" ");
String str2 = words[0] + " ";
String str3 = words[words.length - 1] ;
}
but i don't know how to output the characters. Could someone help me?
I don't know if I should use if, switch, for, do, or do-while...... I'm confused.
what you need is to build up logic for your problem. First break the problem statement and start finding solution for that. Here you go for steps,
Read every character from a string.
Add it to a collection, but before adding that, just check whether it exists.
If it exists just remove it and continue the reading of characteer.
Once you are done with reading the characters, just print the contents of collection to console using System.out.println.
I will recommend you to refer books like "Think like A Programmer". This will help you to get started with logic building.
Just a hint: use a hash map (http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html).
Adding following code after last line of your main program will resolve your issue.
char[] strChars = str2.toCharArray();
String newStr="";
for (char c : strChars) {
String charStr = ""+c;
if(!str3.contains(charStr.toLowerCase()) && !str3.contains(charStr.toUpperCase())){
newStr+=c;
}
}
System.out.println(newStr);
This code loops through all the characters of the first word and check if the second string contains that character (In any form of case Lower or Upper). If it is not containing, adding it to output string and at the end printing it.
Hope this will work in your case.
How about doing it in just 1 line?
str = str.replaceAll("(.)(?=.*\\1)", "");

Character Concatenation Resulting in Numerical Output [duplicate]

This question already has answers here:
In Java, is the result of the addition of two chars an int or a char?
(8 answers)
Closed 9 years ago.
In a programming language called Java, I have the following line of code:
char u = 'U';
System.out.print(u + 'X');
This statement results in an output like this:
173
Instead of
UX
Am I missing something? Why isn't it outputing 'UX'? Thank you.
Because you are performing an addition of chars. In Java, when you add chars, they are first converted to integers. In your case, the ASCII code of U is 85 and the code for X is 88.
And you print the sum, which is 173.
If you want to concatenate the chars, you can do, for example:
System.out.print("" + u + 'X');
Now the + is not a char addition any more, it becomes a String concatenation (because the first parameter "" is a String).
You could also create the String from its characters:
char[] characters = {u, 'X'};
System.out.print(new String(characters));
In this language known as Java, the result of adding two chars, shorts, or bytes is an int.
Thus, the integer value of U (85) is added to the integer value of X (88) and you get an integer value of 173 (85+88).
To Fix:
You'll probably want to make u a string. A string plus a char will be a string, as will a string plus a string.
String u = "U"; // u is a string
System.out.print(u + 'X'); // string plus a char is a string
String u = "U";
System.out.print(u + "X");
instead of char type use String class or StringBuilder class
Another way to convert one of the characters to a string:
char u = 'U';
System.out.print(Character.toString(u) + 'X');
This way could be useful when your variable is of type char for a good reason and you can't easily redeclare it as a String.
That "language called Java" bit amused me.
A quick search for "java concatenate" (which I recommend you do now and every time you have a question) revealed that most good Java programmers hate using + for concatenation. Even if it isn't used numerically when you want string concatenation, like in your code, it is also slow.
It seems that a much better way is to create a StringBuffer object and then call its append method for each string you want to be concatenated to it. See here: http://www.ibm.com/developerworks/websphere/library/bestpractices/string_concatenation.html

what happens when converting char to string? (Java) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
I'm using String.valueOf to convert char to string. But the return value seems not exactly same as a string of the same letter. Codes below:
String myString = "s";
char myChar = 's';//both string and char are assigned as letter 's'
String stringFromChar = String.valueOf(myChar);
if (myString == stringFromChar) {
out.println("equal");
} else {
out.println("not equal");
}
Every time it prints not equal. Please help, thanks! :)
== compare the reference, not the actual value. You must use equals to compare the value.
Read this article if you don't understand it's clear and simple.
NEVER DO THIS AGAIN!!! PROMISE ME!!! =P
When comparing strings always, always, always use the equals method. See Below!
String myString = "s";
char myChar = 's';//both string and char are assigned as letter 's'
String stringFromChar = String.valueOf(myChar);
if (myString.equals(stringFromChar)) {
System.out.println("equal");
} else {
System.out.println("not equal");
}
}
what happens when converting char to string?
Well, you are using the String.valueOf(char) method, whose javadoc does not say how it does the conversion. But the behaviour you are seeing strongly suggests that the JVM you are using creates a new String object each time you call the method.
But you should depend on this happening.
The bottom line is that you should always use the equals method to compare strings. Comparing strings with == will often give you false negatives ... depending on how the strings were created / obtained. You've just been bitten by that. Learn.
Reference:
How do I compare strings in Java?

Categories

Resources