I have an array of characters. I should remove any duplicate characters. I did comparison between the string elements with an array of alphabets. There is another array that acts as counter for any duplictae alphabet. If any character has been found for more than once, I should remove the duplicated character and shif the elements to left. Below is the code. I get error at the line with the comment. Java needs the left hand side of the assignment to be variable. Can you help?
import java.util.ArrayList;
import java.util.Scanner;
public class removeduplicate {
public static void main (String args[])
{
Scanner s=new Scanner(System.in);
String str="abbsded";
String myChars="abcdefghijklmnopqrstuvwxyz";
int[] myCounter=new int[26];
for (int i=0; i<str.length(); i++)
{
for(int j=0; j<myChars.length(); j++)
{
if(str.charAt(i)==myChars.charAt(j))
{
myCounter[j]++;
if (myCounter[j]>1)
{
System.out.println("duplication found in "+ str.charAt(i));
for(int h=i; h<str.length();h++)
{
//this line does not work.
str.charAt(h)=str.charAt(h-1);
}
}
}
}
}//end for
}
}
You can use a Hashmap to keep track of the characters you have run into during your implementation. Then just increment every time you see a character in the alphabet. Only adding a letter to the returned string if the character hasn't been seen before.
public static String removeDuplicates(String input)
{
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
input = input.toUpperCase();
HashMap<Character, Integer> charData = new HashMap<>();
//create the map to store counts of all the chars seen
for(int i = 0; i < alphabet.length(); i++)
charData.put(alphabet.charAt(i), 0);
String cleanedInput = "";
for(int index = 0; index < input.length(); index++)
{
char letter = input.charAt(index);
if(charData.containsKey(letter))
{
charData.put(letter, charData.get(letter) + 1);
//if count is 1 then its the first time we have seen it
if(charData.get(letter) == 1)
{
cleanedInput += letter;
}
}
}
return cleanedInput.toLowerCase();
}
Example Call
public static void main(String[] args) {
System.out.println(removeDuplicates("abbsded"));
System.out.println(removeDuplicates("abbsded!!!"));
System.out.println(removeDuplicates("hahahahahahahahahah"));
}//main method
Output
absde
absde
ha
Note: it only returns the characters once and no characters that aren't in the alphabet are considered in the new trimmed String.
Related
For Example:
Enter a String:
aAaAaAaAaAaAbBbBbBbBbBbBbcCccccCCccCCCC
What character should be converted to uppercase?
b
What the output should be:
aAaAaAaAaAaABBBBBBBBBBBBBcCccccCCccCCCC
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a String");
StringBuilder sb = new StringBuilder(keyboard.nextLine());
System.out.println("Which character should be converted to uppercase?");
char c = keyboard.nextLine().charAt(0);
ParsingUtils.changeLetter(sb, c);
System.out.println(sb);
}
public static void changeLetter(StringBuilder sb, char letter)
{
String change = Character.toString(letter); //changes the char in the parameter to string
String change2 = change.toUpperCase(); //make an uppercase copy of the string
char upper = change2.charAt(0); //change the upper case copy to a char
for (int counter = 0; counter < sb.length(); counter++) //Is supposed to replace every instance of the given character with uppercase
{
if (sb.toString().contains(change))
{
sb.setCharAt(counter, upper);
}
}
}
What my code outputs: BBBBBBBBBBBBBBBBBBBBBBBBBcCccccCCccCCCC
Is there a better, less convoluted way to do this that I'm too frustrated to see?
I'm still a novice in Java so there is probably a simple answer that is going completely over my head.
The first three lines can be simplified to just:
char upper = Character.toUpperCase(letter);
Use charAt(counter), rather than checking if the whole string builder contains the letter.
if (sb.charAt(counter) == letter)
Full code:
public static void changeLetter(StringBuilder sb, char letter)
{
char upper = Character.toUpperCase(letter);
for (int counter = 0; counter < sb.length(); counter++)
{
if (sb.charAt(counter) == letter)
{
sb.setCharAt(counter, upper);
}
}
}
I want to build a simple dictionary search program without using dictionary library. I want to search the string array if the string in array is equal to the char array. It should print the string and its index number. If there are 2 strings that are matching the char then it should print the first string and leave the after string
.e.g String array["fine","rest","door","shine"] char character ['t','r','e','s']. the answer should be "rest" at index 1. and if the String rest is repeat then it should only print first one.
I tried to compare the string array and char array but its returning all the words of string array that matches char array.
String strArray[]=new String[4];
char chrArray[]=new char[4];
String value="";
char compare;
System.out.println("Enter the words :");
for(int i=0;i<strArray.length;i++){
strArray[i]=input.next();
}
System.out.println("Enter the Characters :");
for (int i = 0; i < chrArray.length; i++) {
chrArray[i]=input.next().charAt(0);
}
for (int i = 0; i < strArray.length; i++) {
if(strArray[i].length()==chrArray.length){
if(""+strArray[i]!=value){
value="";
}
for (int j = 0; j < strArray[i].length(); j++) {
for (int k = 0; k < chrArray.length; k++) {
if(strArray[i].charAt(j)==chrArray[k]){
value=value+strArray[i].charAt(j);
}
}
}
}
}
System.out.println(value);
The output should be the string from array that is equal to char array.
You can sort char array and then compare it using Arrays.equal. By sorting char array, there will be no need to use 2 for loops.
import java.util.Arrays;
import java.util.Scanner;
public class Bug {
public static void main(String[] args) {
String strArray[]=new String[4];
char chrArray[]=new char[4];
Scanner input = new Scanner(System.in);
System.out.println("Enter the words :");
for(int i=0;i<strArray.length;i++){
strArray[i]=input.next();
}
System.out.println("Enter the Characters :");
for (int i = 0; i < chrArray.length; i++) {
chrArray[i]=input.next().charAt(0);
}
Arrays.sort(chrArray);
for (int i = 0; i < strArray.length; i++) {
char[] x = strArray[i].toCharArray();
Arrays.sort(x);
if(Arrays.equals(chrArray, x))
{
System.out.println(strArray[i]);
break;
}
}
}
}
You could also create a Map<Character, Integer> to store counts for both the words and the characters, and compare each word character counts with the character counts. If both are equal, print it out.
Demo:
import java.util.Map;
import java.util.HashMap;
public class Example {
private static final String[] words = {"fine", "rest", "door", "shine"};
private static final char[] chars = {'t', 'r', 'e', 's'};
/**
* Initialise String character counts in a hashmap datastructure.
* #param word The string word to iterate.
* #return Hashmap of character -> counts.
*/
private static Map<Character, Integer> getCharCounts(String word) {
Map<Character, Integer> wordCounts = new HashMap<>();
for (int i = 0; i < word.length(); i++) {
Character character = word.charAt(i);
// If key doesn't exist, initialise it
if (!wordCounts.containsKey(character)) {
wordCounts.put(character, 0);
}
// Increment count by 1
wordCounts.put(character, wordCounts.get(character) + 1);
}
return wordCounts;
}
public static void main(String[] args) {
// Initialise character counts first
Map<Character, Integer> charCounts = getCharCounts(String.valueOf(chars));
for (int i = 0; i < words.length; i++) {
Map<Character, Integer> wordCounts = getCharCounts(words[i]);
// If Hashmaps are equal, then we have found a match
if (wordCounts.equals(charCounts)) {
System.out.println(words[i] + ", at index = " + i);
break;
}
}
}
}
Output:
rest, at index = 1
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("type the sentence you want to find the letters of");
String sentence = s.nextLine();
getLetters(sentence);
}
public static void getLetters(String sentence) {
int count;
char ch[] = sentence.toCharArray();
for (int i = 0; i < sentence.length(); i++) {
System.out.print(ch[i]);
}
}
I am trying to display the occurrence of each letter (letter only) in a sentence, and I am lost. I have converted the string into a char array, but I am now lost.
For instance, if I typed the sentence: "Hello, how are you?"
The result would be:
Occurrence of h: 1
Occurrence of e: 2
Occurrence of l: 2
Occurrence of o: 3
etc..
I know I need to utilize my int count, but I am not sure how to do that. Our professor is having us use this:
c[26];
c[ch - 'a']++;
And I'm not sure where to use those for this little project.
Edit: Update
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("type the sentence you want to find the letters of");
String sentence = s.nextLine();
getLetters(sentence);
}
public static void getLetters(String sentence) {
sentence = sentence.toLowerCase();
int count[];
char ch[] = sentence.toCharArray();
for (int i = 0; i < sentence.length(); i++) {
System.out.print(ch[i]);
}
char alphabet[] = "abcdefghijklmnopqrstuvwxyz".toCharArray();
System.out.println();
}
}
Use a HashMap<Character, Integer> to keep track. The key is a unique character, and the integer counts the number of times you see it.
import java.util.HashMap;
public class J {
public static void main(String[] args) {
String string = "aaaabbbccd";
HashMap<Character, Integer> map = frequency(string);
System.out.println(map);
}
public static HashMap<Character, Integer> frequency(String string) {
int length = string.length();
char c;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
// loop thru string
for (int i = 0; i < length; i++) {
c = string.charAt(i);
// If u have already seen that character,
// Increment its count
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
// otherwise this is the first time u
// have seen it, so set count to 1
} else {
map.put(c, 1);
}
}
return map;
}
}
Output:
{a=4, b=3, c=2, d=1}
I don't see reason to use HashMap here. HashMaps are used to map some values into places in memory for faster access, using HashFunction. In this case he will have same, or very similar thing with array and this mapping function that is given to him(ch-'a') . Also, for someone who is doing this, it is maybe too soon for HashMap.
Your problem is that you haven't understood idea.
Letters in java have values (You can check ASCII table). You have 26 letters in alphabet, first one is 'a' and last is 'z'. So you want to have array of 26 elements. Every time when you have 'a' into your string, you want to increment element in place 0 in array, when you come into 'b' you want to increment element in place 1.... when you come to 'z' element 25. So, in fact with (ch-'a') you map your letter in place in array where is count of its ocurrence.
You take string, do .toLowerCase() case on it, pass it once to count letters, then print what you found.
This is the initial challenge I'm trying to address
1) takes two arguments—a “source" English word in a string, and an English dictionary supplied in an array
2) returns a list of English words as an array
The words returned are those from the dictionary that have four consecutive letters (or more) in common with the “source” word. For example, the word MATTER has the four letters in a row “ATTE" in common ATTEND.
The code however gives me errors with the substring
Below is the code for your reference.
public class FourLetterInCommon {
static String wrd = "split";
static String[] d = new String[]{"SPLITS", "SPLITTED", "SPLITTER", "SPLITTERS", "SPLITTING", "SPLITTINGS", "SPLITTISM", "SPLITTISMS", "SPLITTIST", "SPLITTISTS"};
public static void main(String[] args){
System.out.println(fourletters (wrd, d));
}
public static List<String> fourletters (String word, String[] dict){
int dictsize = dict.length;
int wordlength = word.length();
List<String> Commonletters = new ArrayList<String>();
for(int i = 0; i<=dictsize; i++) {
for (int j=0; j<=wordlength;) {
if(dict[i].contains(word.substring(i, 5)))
{
Commonletters.add(dict[i]);
}
break;
}
}
return Commonletters;
}
}
This is the error message I get:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(Unknown Source) at FourLetterInCommon.fourletters(FourLetterInCommon.java:22) at FourLetterInCommon.main(FourLetterInCommon.java:10)
What does the errors mean? Apologies, but a bit clueless at this stage.
Quite a few issues here.
1)
for(int i = 0; i<=dictsize; i++) {
should be
for(int i = 0; i<dictsize; i++) {
2)
for (int j=0; j<=wordlength;) {
should be
for (int j=0; j<=wordlength-4; j++) {
3)
if(dict[i].contains(word.substring(i, 5)))
should be
if(dict[i].contains(word.substring(j, j+4)))
4)
I don't believe you really want to break; there. I'm guessing you want to break when you find a match, so it should be inside the if statement.
Corrected code:
public class FourLetterInCommon
{
static String wrd = "SPLIT";
static String[] d = new String[] { "SPLITS", "SPLITTED", "SPLITTER", "SPLITTERS", "SPLITTING", "SPLITTINGS",
"SPLITTISM", "SPLITTISMS", "SPLITTIST", "SPLITTISTS" };
public static void main(String[] args)
{
System.out.println(fourletters(wrd, d));
}
public static List<String> fourletters(String word, String[] dict)
{
int dictsize = dict.length;
int wordlength = word.length();
List<String> Commonletters = new ArrayList<String>();
for (int i = 0; i < dictsize; i++)
{
for (int j = 0; j <= wordlength - 4; j++)
{
if (dict[i].contains(word.substring(j, j + 4)))
{
Commonletters.add(dict[i]);
break;
}
}
}
return Commonletters;
}
}
Output:
[SPLITS, SPLITTED, SPLITTER, SPLITTERS, SPLITTING, SPLITTINGS, SPLITTISM, SPLITTISMS, SPLITTIST, SPLITTISTS]
The following line would throw an Exception:
if(dict[i].contains(word.substring(i, 5)))
Here, i ranges from 0 to dict.length which is 10 in this case. word contains 5 characters only. So, accessing any character from index 5 onwards would throw an Exception.
If you want to check for certain number of characters then you should use this:
for (int j=0; j < wordlength;) {
if(dict[i].contains(word.substring(j, wordlength - j)))
I was trying out this question :
Write a function using Recursion to display all anagrams of a string entered by the user, in such a way that all its vowels are located at the end of every anagram. (E.g.: Recursion => Rcrsneuio, cRsnroieu, etc.) Optimize it.
From this site :
http://erwnerve.tripod.com/prog/recursion/magic.htm
This is what i have done :
public static void permute(char[] pre,char[] suff) {
if (isEmpty(suff)) {
//result is a set of string. toString() method will return String representation of the array.
result.add(toString(moveVowelstoEnd(pre)));
return;
}
int sufflen = getLength(suff); //gets the length of the array
for(int i =0;i<sufflen;i++) {
char[] tempPre = pre.clone();
char[] tempSuf = suff.clone();
int nextindex = getNextIndex(pre); //find the next empty spot in the prefix array
tempPre[nextindex] = tempSuf[i];
tempSuf = removeElement(i,tempSuf); //removes the element at i and shifts array to the left
permute(tempPre,tempSuf);
}
}
public static char[] moveVowelstoEnd(char[] input) {
int c = 0;
for(int i =0;i<input.length;i++) {
if(c>=input.length)
break;
char ch = input[i];
if (vowels.contains(ch+"")) {
c++;
int j = i;
for(;j<input.length-1;j++)
input[j] = input[j+1];
input[j]=ch;
i--;
}
}
return input;
}
Last part of the question is 'Optimize it'. I am not sure how to optimize this. can any one help?
Group all the vowels into v
Group all consonants into w
For every pair of anagrams, concat the results