This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
So when I'm running this code with any word, it is always returning false. The first String accepts the word, and then it's changed to lower case. Then I'm building a new String out of it to compare it to another string that is appended as the reverse of the original word. Am I not seeing something, or can you tell me what's wrong with it?
public class Palindromes
{
public static void main(String[] args)
{
int count = Integer.parseInt(args[0]);
for(int i = 1; i <= count; i++)
{
System.out.print(isPalindrome(args[i]) + " ");
}
}
public static boolean isPalindrome(String s)
{
String str = s.toLowerCase();
StringBuilder orig_str = new StringBuilder(str);
StringBuilder revStr = new StringBuilder();
for (int i = str.length()-1; i >= 0; i--)
{
revStr.append(orig_str.charAt(i));
}
boolean isPal = (revStr == orig_str);
return isPal;
}
}
Comparing two distinct StringBuilder instances with == would always give you false, regardless of their content, since they are not the same instance.
Try revStr.toString().equals(str)
It seems that StringBuilder doesn't override Object's equals, so you have to perform the equals on the Strings that result from the StringBuilders.
BTW, StringBuilder has a reverse method, so you can re-write your method in a single line :
public static boolean isPalindrome(String s) {
return new StringBuilder(s.toLowerCase()).reverse().toString().equals(s.toLowerCase());
}
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
Hi I'm trying to build a palindrome but it seem to be not working, please could you help. I'm expected to catch true on dad and false on other things
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter Your User Name");
String userInput =input.nextLine();
System.out.println(abcDEF(userInput));
}
static boolean abcDEF(String userInput) {
StringBuilder s1 = filter(userInput);
StringBuilder s2 = reverse(userInput);
return s1.toString() == s2.toString();
}
static StringBuilder filter(String userInput) {
StringBuilder sb = new StringBuilder();
char[] inputData = userInput.toCharArray();
for (int i = 0; i < userInput.length(); i++) {
if (userInput.matches("[a-zA-Z0-9]+")) {
sb.append(inputData[i]);
}
}
return sb;
}
static StringBuilder reverse(String userInput) {
StringBuilder sb = filter(userInput);
sb.reverse();
return sb;
}
change your abcDEF() to this(last line):
static boolean abcDEF(String userInput) {
StringBuilder s1 = filter(userInput);
StringBuilder s2 = reverse(userInput);
return s1.toString().equals(s2.toString());
}
You are comparing the references of two strings in your code, which is not same in your case. Rather, you should compare the content of the strings. And this is how String contents are compared.
This question already has answers here:
Replace a character at a specific index in a string?
(9 answers)
Closed 5 years ago.
I need this program to replace all r's with h's if they follow a vowel.
This is just a test program, my actual assignment is to replace all the r's in the "Jaws" script with h's that follow a vowel, and do other various task to that string.
public static void main(String[] args) {
String s = "Hey, I'm from boston. harbor, fotter, slobber, murder.";
System.out.println(replace(s));
}
//this method should replace r with h if it follows a vowel.
public static String replace(String s) {
String newS = "";
String vowels ="aeiouAEIOU";
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == 'r' && isVowel(s.charAt(i-1))) {
newS = s.replace("r", "h");
}
}
return newS;
}
//this method will check if a character is a vowel or not.
public static Boolean isVowel(char s) {
String vowels="aeiouAEIOU";
if (vowels.contains("" + s)) {
return true;
}
return false;
}
}
Please use String builder to replace at specific index as said Replace a character at a specific index in a string?
Below how your replace method should look like
public static String replace(String s) {
StringBuilder myName = new StringBuilder(s);
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == 'r' && isVowel(s.charAt(i - 1))) {
myName.setCharAt(i, 'h');
}
}
return myName.toString();
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I am trying to figure out how to read a list of Strings in a text file and return the position of the word found. I'm not sure why this isn't working. Can someone tell me what I'm doing wrong? It returns -1 for each word and the words are definitely in there.
public class LinearSearch extends SearchAlgorithm
{
public int search(String[] words, String wordToFind) throws ItemNotFoundException {
for (int i = 0; i < words.length; i++) {
if (words[i] == wordToFind) {
return i;
}
else {
return -1;
}
}
return -1;
}
public final static String FILE_AND_PATH = "longwords.txt";
/*
* TODO: Be sure to change the FILE_AND_PATH to point to your local
* copy of longwords.txt or a FileNotFoundException will result
*/
//Note how we deal with Java's Catch-or-Declare rule here by declaring the exceptions we might throw
public static void main(String[] args) throws FileNotFoundException {
File file = new File("/Users/myName/Desktop/compsci/HOMEWORK/recursion/longwords.txt");
Scanner input = new Scanner(file);
int wordCount = 0;
ArrayList<String> theWords = new ArrayList<String>();
//read in words, count them
while(input.hasNext()) {
theWords.add( input.next() );
wordCount++;
}
//make a standard array from an ArrayList
String[] wordsToSearch = new String[theWords.size()];
theWords.toArray(wordsToSearch);
//start with the linear searches
tryLinearSearch(wordsToSearch, "DISCIPLINES");
tryLinearSearch(wordsToSearch, "TRANSURANIUM");
tryLinearSearch(wordsToSearch, "HEURISTICALLY");
tryLinearSearch(wordsToSearch, "FOO");
You can't compare Strings with words[i] == wordToFind. You have to use words[i].equals(wordToFind).
You also should remove the else block within the for loop.
Your loop is returning on the first iteration. Remove the else block.
Basically i am trying to create an algorithm that will test whether a given string is a cover string for a list of strings. A string is a cover string if it contains the characters for every string in the list in a way that maintains the left to right order of the listed strings. For example, for the two strings "cat" and "dog", "cadhpotg" would be a cover string, but "ctadhpog" would not be one.
I have created an algorithm however it is producing the output true when the output should be false, as the given string is a cover String for Strings list1 and list2, but not for list3.
Any help into why this algorithm is producing the wrong output would be highly appreciated.
public class StringProcessing2 {
//ArrayList created and 3 fields added.
public static ArrayList<String> stringList = new ArrayList<>();
public static String list1 = "phillip";
public static String list2 = "micky";
public static String list3 = "fad";
//Algorithm to check whether given String is a cover string.
public static boolean isCover(String coverString){
int matchedWords = 0;
stringList.add(list1);
stringList.add(list2);
stringList.add(list3);
//for-loops to iterate through each character of every word in stringList to test whether they appear in
//coverString in left to right order.
for(int i = 0; i < stringList.size(); i++){
int countLetters = 1;
for(int n = 0; n < (stringList.get(i).length())-1; n++){
if(coverString.indexOf(stringList.get(i).charAt(n)) <= (coverString.indexOf((stringList.get(i).charAt(n+1)),
coverString.indexOf((stringList.get(i).charAt(n)))))){
countLetters++;
if(countLetters == stringList.get(i).length()){
matchedWords++;
}
}
}
}
if(matchedWords == stringList.size()){
return true;
}
else
return false;
}
public static void main(String[] args) {
System.out.println(isCover("phillmickyp"));
}
}
Probably the easiest way to go about this is to break down the problem into parts. Have every function do the least possible work while still getting something done towards the overall goal.
To accomplish this, I'd recommend creating a helper method that takes two Strings and returns a boolean, checking if one String is the cover of another.
boolean isCover(String s, String cover)
{
int i = 0;
for(char c : s.toCharArray())
if((i = cover.indexOf(c, i)) == -1)
return false;
return true;
}
Then once you have something that can correctly tell you if it's a valid cover String or not, it becomes much simpler to check if one String is a valid cover for multiple Strings
boolean isCover(List<String> strings, String cover)
{
for(String s : strings)
if(!isCover(s, cover))
return false;
return true;
}
Language : Java
Key Notes: *Needs to loop through a String using either a For loop or While loop
*It removes the duplicate letter(s) of the String and returns the word without the dupilcates.
Eg: The string is HELLO - The method then loops through and removes any duplicates, in this case " L " and returns in the end HELO
i have this so far
private String removeAnyDuplicates(String userWord)
{
//Code goes here?
return "" ; // Need to return the new string
}
You can do that with regular expressions. e.g.:
private static final Pattern REGEX_PATTERN =
Pattern.compile("(.)\\1*");
public static void main(String[] args) {
String input = "HELLO, AABBCC";
System.out.println(
REGEX_PATTERN.matcher(input).replaceAll("$1")
); // prints "HELO, ABC"
}
I'm assuming that removing duplicates means that the result contains at most one occurrence of any character. (Some of the other answers assume that adjacent duplicates only need to be reduced to single occurrences.) The basic algorithm would be:
initialize the result to the empty string
loop through each character of the input and if the character is not already present in the result, append it to the result
return the result
A naive (and very inefficient) implementation would be:
private String removeAnyDuplicates(String userWord)
{
String result = "";
for (int i = 0; i < userWord.length(); ++i) {
char c = result.charAt(i);
if (result.indexOf(c) < 0) {
// negative index indicates not present
result += String.valueOf(c);
}
}
return result;
}
This has two major sources of inefficiency: it creates many intermediate String objects and it has to scan the entire result so far for each character of the input. These problems can be solved by using some other built-in Java classes—a StringBuilder to more efficiently accumulate the result and a Set implementation to efficiently record and test which characters have already been seen:
private String removeAnyDuplicates(String userWord)
{
int len = userWord.length();
StringBuilder result = new StringBuilder(len);
Set<Character> unique = new HashSet<Character>();
for (int i = 0; i < len; ++i) {
char c = result.charAt(i);
// try to add c to set of unique characters
if (unique.add(c)) {
// if it succeeds, this is the first time seeing c
result.append(c);
}
}
return result.toString();
}
private String removeAnyDuplicates(String userWord)
{
CharSequence inputStr = userWord;
int length = inputStr.length();
Set<Character> uniqueChars = new HashSet<Character>();
for(int i=0; i < length; ++i) {
uniqueChars.add(inputStr.charAt(i));
}
return uniqueChars.size() >= 3;
}
check out this answer
Convert the string to an array of char, and store it in a LinkedHashSet. That will preserve your ordering, and remove duplicates.
Like this:
private static String removeAnyDuplicates(String userWord)
{
char[] chars = userWord.toCharArray();
Set<Character> charSet = new LinkedHashSet<Character>();
for (char c : chars) {
charSet.add(c);
}
StringBuilder sb = new StringBuilder();
for (Character character : charSet) {
sb.append(character);
}
return sb.toString();
}
Remember:
import java.util.LinkedHashSet;
import java.util.Set;
You can try this
public static void main(String args[]){
System.out.println(removeAnyDuplicates("HELLO"));
}
private static String removeAnyDuplicates(String userWord)
{
char[] arr=userWord.toCharArray();
List<String> list=new ArrayList<>();
for(int i=0;i<arr.length;i++){
if(!list.contains(String.valueOf(arr[i]))){
list.add(String.valueOf(arr[i]));
}
}
return list.toString().replaceAll("\\[|\\]|\\,","") ;
}
Try this one liner:
private String removeAnyDuplicates(String userWord) {
return userWord.replaceAll("(.)\\1+", "$1");
}
This uses a regular expression to find repeated (2 or more) letters and replaces them with a single instance of the letter.
It is unclear if "repeated" means appearing immediately after or anywhere after. For anywhere, use this:
private String removeAnyDuplicates(String userWord) {
return userWord.replaceAll("(.)(?=.*\\1)", "");
}