Input in Char Array without Duplicates Java - java

Imagine I have this:
String input = "AB BC"; // ( Just an Example)
I want to put this String into an char array, but i want to have no duplicates
and blank symbols in my char Array. My solution so far:
String input = "AB BC"
char array[]=input.toCharArray();
for(int i=0;i<array.length;i++){
System.out.println("Data at ["+i+"]="+array[i]);
}
The Output is :
This is my input String AB BC
This is the content of my Char Array
Data at [0]=A
Data at [1]=B
Data at [2]=
Data at [3]=
Data at [4]=B
Data at [5]=C
Data at [6]=
So now I don't know how I can erase the duplicates and the blank symbols.

Transfer content to LinkedHashSet . It will remove the duplicates for you !
Here's an example to start with.

You can use a LinkedHashSet<Character> (to maintain insertion order).
Use the replaceAll method on your String object to replace whitespaces
Transform your String in a char array
For each char add it to the Set (a Set doesn't allow duplicates)
Use toArray(T[] object) method to get back a Character array.
So it would be something like this :
String input = "AB BC";
input = input.replaceAll("\\s+", "");
Set<Character> s = new LinkedHashSet<>();
for(char c : input.toCharArray())
s.add(c);
Character [] array = s.toArray(new Character[0]);
System.out.println(Arrays.toString(array));
Output :
[A, B, C]
If you want to have back an array of primitive you can use (note that you have to use the apache commons library) char[] arr = ArrayUtils.toPrimitive(array);
Here's the source code :
2647 public static char[] toPrimitive(Character[] array) {
2646 if (array == null) {
2647 return null;
2648 } else if (array.length == 0) {
2649 return EMPTY_CHAR_ARRAY;
2650 }
2651 final char[] result = new char[array.length];
2652 for (int i = 0; i < array.length; i++) {
2653 result[i] = array[i].charValue();
2654 }
2655 return result;
2656 }

this will add only the chars without any blanks to the hashset
char array[]=input.toCharArray();
Set<Character> m=new LinkedHashSet<Character>();
for(int i=0;i<array.length;i++){
if(array[i]!=' ')
m.add(array[i])
}
Character[] text = m.toArray(new Character[0]);
System.out.println(Arrays.toString(text))

use Hashset of generic type character
HashSet<Character> m=new HashSet<Character>();

You could use a LinkedHashSet but I assume you want an array at the end. You can do this.
String input = ...
StringBuilder sb = new StringBuilder();
BitSet seen = new BitSet(); // more compact than a HashSet<Character>
seen.set(' '); // pretend we have seen space already
for(char ch: input.toCharArray()) {
if(!seen.get(ch)) {
sb.append(ch);
seen.set(ch);
}
}
char[] unique = sb.toString().toCharArray();

Simply you can try this:
String input = "AB BC";
char array[]=input.toCharArray();
for(int i=0;i<array.length;i++){
if(!input.substring(0,i).contains(array[i]+"") && array[i]!=' ')
System.out.println("Data at ["+i+"]="+array[i]);
}
Output:
Data at [0]=A
Data at [1]=B
Data at [5]=C

Related

Comparing if a string's character exist in an array of characters

I want the user to input a string, then I want to check if each charachter in this string exists in an array of charachters I created. Even if it's not in the correct order.
The way I go about it is initialise the array of chars then through using the scanner have a String input from the user.
public static char[]aa={'A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y','U','O','B','J','Z','X'};
I created a function
private static void isValidSequence(String sequence, char[] k) {
outter :for (int j = 0; j < sequence.length(); j++) {
for (int i = 0; i < k.length; i++) {
if(sequence.charAt(j) == k[i]){
break;
} else {
System.out.println("invalid");
break outter;
}
}
}
}
What happens is that if for example the first letter of the the string doesn't match the first input of array it gives me an 'invalid' input. How can I go around that? and make it iterate through the whole array of characters before giving the invalid output.
An approach would be to sort your array, and then use the Binary Search Algorithm (BSA):
// sort the array once
Arrays.sort(aa);
// iterate over the input string
for(int i = 0, length = sequence.length(); i < length; i++) {
// the java implementation of the BSA returns negative numbers for not found elements
if(Arrays.binarySearch(aa, sequence.charAt(i)) < 0) {
// char was not found, break loop
return;
}
}
Note: If the array is not sorted / can not be sorted, then the BSA is useless and will produce undefined results.
Note 2: The BSA is faster (O(log n)) than simple iteration (O(n))
This can also be done as below :
char[]aa={'A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y','U','O','B','J','Z','X'};
String s = "aStrinG";
for (char c : s.toCharArray()) {
for (char c2 : aa) {
if (c2 == c) {
System.out.println("String char " + c + " exists in char array");
}
}
}
It produces :
String char S exists in char array
String char G exists in char array
Best way is to use SET instead of an Array. A set contains no duplicate elements and then simply you can use it using the method contains()
Using Java 9 (Unmodifiable Sets)
Set<Character> alphabetSet = Set.of('A', 'B', 'C');
//Another way
//Set<Character> alphabetSet = new HashSet<>(Arrays.asList('A', 'B', 'C'));
for(char c: sequence)
{
if(alphabetSet.contains(c)){
//do something
}
else{
//do something
}
}
Read more about Set:
https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
To directly answer your question:
Solution 1:
Use continue instead of break this will print "invalid" each time a character is not in k.
Solution 2:
You can use a counter and increment it every time you have a character not in k, then outside the loop you will have visibility on how many invalid characters you have.
Solution 3:
If you want even more detail you can have a list of characters and add each invalid character to this list. This will give you visibility on exactly what characters are invalid.
I am not sure what you are trying to do so I don't know which method is better for you, you can also use an altogether approach using streams for example.
If you start using the Collection provided, you could use a Set to do your checks.
First, convert the array into the Set :
char[] array = "abcdefghijklmnopqrstuvwxyz".toCharArray();
Set<Character> setAllowed = new TreeSet<>();
for(char c : array){
setAllowed.add(c);
}
Then, you just have to iterate and check for each character. I would add another Set to retrieve every characters not allowed, giving a better output.
Set<Character> setError = new TreeSet<>();
for(char c : s.toCharArray()){
if(setAllowed.contains(c)){
setError.add(c);
}
}
Test :
public static void main(String[] args) {
String s = "foobar123";
char[] array = "abcdefghijklmnopqrstuvwxyz".toCharArray();
//INIT
Set<Character> setAllowed = new TreeSet<>();
Set<Character> setError = new TreeSet<>();
for(char c : array){
setAllowed .add(c);
}
//RESEARCH
for(char c : s.toCharArray()){
if(setAllowed.contains(c)){
setError.add(c);
}
}
//OUTPUT
System.out.println(setError);
}
[1, 2, 3]

Take a List of Strings and double each character in an arraylist

I am trying to double each letter in a list of Strings in an array loop.
For example:
["abc","def"] --> ["aabbcc","ddeeff"]
ArrayList<String> aa;
aa = new ArrayList<String>();
String res = "";
for(int i=0;i<words.size();i++){
char at = aa.get(i);
res=res+at+at;
}
return res;
I am still new to coding and as you can see, my code is a mess. Help is appreciated. Thanks in advance
You some problems with your implementation:
You interact over words array but uses the index over the aa. As it was never added items to it, you will get an ArrayIndexOutOfBoundsException.
You issue a return res but this will return only one string, not an array of words.
According to your example this can be done this way:
public static ArrayList<String> doubleWords(ArrayList<String> input) {
ArrayList<String> result = new ArrayList<>();
for (String string : input) {
String word = "";
for (int i = 0; i < string.length(); i++) {
word += ""+string.charAt(i)+string.charAt(i);
}
result.add(word);
}
return result;
}
Your output for an ArrayList with [abc, def] will be [aabbcc, ddeeff].
You need to iterate through your list of words and then for each word in the list iterate through the characters in the string, like so:
public ArrayList<String> doubleWords(ArrayList<String> words) {
ArrayList<String> doubledWords = new ArrayList<String>();
for (String word : words) {
String newWord = "";
for (int i=0; i<word.length(); i++) {
newWord = newWord + word.substring(i, i+1) + word.substring(i, i+1);
}
doubledWords.add(newWord);
}
return doubledWords;
}
Since Java 8 this can also be achieved in the following way:
String input = "abc";
StringBuilder builder = new StringBuilder();
input.chars().forEach(value -> builder.append((char)value).append((char)value));
Remeber to convert the int value back to a char before you append it.
Output for above program:
System.out.println(builder.toString());
// aabbcc
//response list
ArrayList<String> aa;
aa = new ArrayList<String>();
StringBuilder sb = new StringBuilder() ;
String word;
// iterate list of words
for(int i=0; i < words.size(); i++){
//get word
word = words.get(i);
//iterate each character in word
for(int j =0; j < words; j++) {
//append each char twice in StringBuilder
sb.append(word[j).append(word[j]);
}
//add word to output list
aa.add(sb.toString());
//empty StringBuilder for next word
sb.setLength(0);
}
return aa;
It can be done only by java stream api without any temporary variables:
List<String> result = listOfWords.stream().
map(value -> String.valueOf( // new result String(doubled word)
value.chars() // get chars for each original string
.mapToObj(i-> (char)i) // cast each char from int to char type
.map(c -> String.valueOf(new char[]{c, c})) // create doubled char string
.collect(Collectors.joining()))) // concatenate all doubled chars
.collect(Collectors.toList()); // collect result to list

How to get Minimum value in list of charecters

here is my doubht
List chars=new ArrayList();
the above list contained values are [A,A,B,B,C,D,E];
i want to get A as output because this is minimum value according to ascii.
how to get this value in java.
This below code block would help you.
List<Character> arr = new ArrayList<Character>();
arr.add('B'); arr.add('H');
arr.add('C'); arr.add('R');
arr.add('D'); arr.add('E');
arr.add('Z'); arr.add('O');
char res = 'z';
for (Character charat : arr) {
if (charat <= res) {
res = charat;
}
}

Compare two Arrays and remove duplicates from Original Array java(no lists)

So I am trying to compare two char arrays, and all letters that are present in keyW, should be removed from the array invAlphabet. I have been able to find the duplicates inside the invAlphabet array, however, I don't know how to remove the duplicate elements without using Lists or Collections which I should not use...
Any idea?
public static void main(String[] args)
{
final int SIZE = 26;
char[] keyW = {'A', 'L','O'};
char[] invAlphabet = new char [SIZE];
for (int i = 0; i < SIZE; i++)
{
invAlphabet[i] = (char)('Z' - i);
}
for (int i = 0; i<keyW.length; i++)
{
for (int j = 0; j < invAlphabet.length; j++)
{
if(keyW[i] == invAlphabet[j])
{
//need to delete the invAlphabet[j] elements that are duplicates
System.out.println(invAlphabet[j]);
System.out.println(j);
break;
}
}
}
}
If you want to solve it in O(n), then you can mark all the character That are present in keyW[] array, and then check and don't add them to your new noDuplicateArray[].
char[] keyW = {'A', 'L', 'O', 'P'};
char[] invAlphabet = {'X', 'A', 'P', 'B', 'C'};
//create boolean array
boolean[] mark = new boolean[128];
Arrays.fill(mark, false);
//mark which characters are present in keyW array
for (char ch : keyW) {
mark[ch] = true;
}
// find number of duplicate character in invAlphabet array
int duplicateCount = 0;
for (char ch : invAlphabet) {
if (mark[ch]) {
duplicateCount++;
}
}
// create new array
// size of new array = invAlphabet array length - duplicate number of character in invAlphabet array
char[] noDuplicateArray = new char[invAlphabet.length - duplicateCount];
//add character in new array
int idx = 0;
for (char ch : invAlphabet) {
if (!mark[ch]) {
noDuplicateArray[idx++] = ch;
}
}
You cannot resize the array object, as you see you could use some other data types. However, if you are allowed to just use array, you can put some other non-alphabetic character in place of removed character. For example '0'. So while using or printing you can skip the character in the array if it is '0'.
Could you use String and replace method?
String invAlphabetString = new String(invAlphabet);
for(char i:keyW){
invAlphabetString=invAlphabetString.replace(""+i, "");
}
char[] invAlphabetWithoutKeyW = invAlphabetString.toCharArray();
System.out.println(Arrays.toString(invAlphabetWithoutKeyW));
I would begin by writing a method to search a char[] for a given char (that is, a contains method) like
private static boolean contains(char[] chars, char ch) {
for (char c : chars) {
if (c == ch) {
return true;
}
}
return false;
}
Then the problem can be decomposed into two steps. First, count the duplicates and second build an output array by copying without the duplicates. Something like
int dupes = 0;
for (char ch : invAlphabet) {
if (contains(keyW, ch)) {
dupes++;
}
}
int i = 0;
char[] noDupes = new char[invAlphabet.length - dupes];
for (char ch : invAlphabet) {
if (!contains(keyW, ch)) {
noDupes[i] = ch;
i++;
}
}
Alternatively, you could convert your keyW array to a String. And, in Java 8+, you could construct a Stream of your characters. Map to the array, filter against the String and then collect to another String. Something like,
String keyWord = new String(keyW);
char[] noDupes = IntStream.range(0, invAlphabet.length)
.mapToObj(x -> invAlphabet[x])
.filter(ch -> (keyWord.indexOf(ch) < 0))
.map(String::valueOf)
.collect(Collectors.joining()).toCharArray();

Sorting characters alphabetically in a String

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);
}

Categories

Resources