Copy String array and remove empty strings - java

I want to eliminate empty elements within my String array. This is what I have tried so far:
String version = null;
String[] xml = new String[str.length];
for(int i = 0; i <= str.length -1; i++)
{
if(str[i] == "")
{
}
else
{
xml[i] = str[i];
}
}
String version = null;
String[] xml = new String[str.length];
for(int i = 0; i <= str.length -1; i++)
{
if(!str[i].equals(""))
{
xml[i] = str[i];
}
}
String version = null;
String[] xml = new String[str.length];
for(int i = 0; i <= str.length -1; i++)
{
if(!str[i].isEmpty())
{
xml[i] = str[i];
}
}
String version = null;
String[] xml = new String[str.length];
for(int i = 0; i <= str.length -1; i++)
{
if(str[i].isEmpty() == false)
{
xml[i] = str[i];
}
}
No matter which one I try, it always copies all the values. I've checked the locals, and it is clear that there are empty arrays within the String array.

Try this,
b = Arrays.copyOf(a, a.length);
Or
b = new int[a.length];
System.arraycopy(a, 0, b, 0, b.length);
Or
b = a.clone();

You are copying the same length array and using the same indexes. The length is always going to be the same.
List<String> nonBlank = new ArrayList<String>();
for(String s: str) {
if (!s.trim().isEmpty()) {
nonBlank.add(s);
}
}
// nonBlank will have all the elements which contain some characters.
String[] strArr = (String[]) nonBlank.toArray( new String[nonBlank.size()] );

String str[] = {"Hello","Hi","","","Happy","","Hmm"};
int count = 0;// Thisreprents the number of empty strings in the array str
String[] xml = new String[str.length];
for(int i = 0,j=0; i <= str.length -1; i++)
{
if(str[i].equals(""))
{
count++;
}
else
{
xml[j] = str[i];j++;
}
}
String a[] = Arrays.copyOfRange(xml, 0, xml.length-count);//s is the target array made by copieng the non-null values of xml
for(String s:a){
System.out.println(s);
}
NOTE : This may not be an efficient solution but it will give the result as per your requirement

This is just an alternate solution since you didn't want ListArray.
Read the comments in the code to clearly understand the logic.
int i,j=0,cnt=0;
//The below for loop is used to calculate the length of the xml array which
//shouldn't have any empty strings.
for(i=0;i<str.length;i++)
if(!isEmpty(str[i])
cnt++;
//Creation of the xml array with proper size(cnt) and initialising i=0 for further use
String xml[]=new String[cnt];
i=0;
//Simply copying into the xml array if str[i] is not empty.Notice xml[j] not xml[i]
while(i<str.length)
{
if(!isEmpty(str[i]))
{
xml[j]=str[i];
i++;
j++;
}
else
i++;
}
That should do the work.
Also I would suggest to not work with the 0th position of array as it kinda creates confusion for .length functions.Thats only my view. If you are comfortable with it,carry on! :D

If you are looking for a high-performance solution I think that this is the best solution. Otherwise if your input array is not so huge, I would use a solution similar to Peter Lawrey one, so it makes your code easy to understand.
With this solution you loop the input array only one, and if you don't need the input array any more you can avoid one array copy calling filterBlankLines with preserveInput = false.
public class CopyingStringArrayIntoNewStringArray {
public static void main(String[] args) {
String[] str = { "", "1", "", null, "2", " ", "3", "" };
System.out.println("\nBefore:");
printArrays(str);
String[] xml = filterBlankLines(str, true);
System.out.println("\nAfter:");
printArrays(xml);
}
private static String[] filterBlankLines(String input[], boolean preserveInput ) {
String[] str;
if (preserveInput) {
str = new String[input.length];
System.arraycopy(input, 0, str, 0, input.length);
} else {
str = input;
}
// Filter values null, empty or with blank spaces
int p=0, i=0;
for (; i < str.length; i++, p++) {
str[p] = str[i];
if (str[i] == null || str[i].isEmpty() || (str[i].startsWith(" ") && str[i].trim().isEmpty())) p--;
}
// Resize the array
String[] tmp = new String[ p ];
System.arraycopy(str, 0, tmp, 0, p);
str = null;
return tmp;
}
private static void printArrays(String str[]) {
System.out.println( "length " + str.length);
for (String s : str ) {
System.out.println(">"+s+"<");
}
}
}
The output:
Before:
length 8
><
>1<
><
>null<
>2<
> <
>3<
><
After:
length 3
>1<
>2<
>3<

This is the best and short way to copy an array into the new array.
System.arraycopy(srcArray, 0, destArray, 1, destArray.length -1);

Related

Text to string array and delete duplicates

The idea of the program is that it gets the text divided by space from the scanner.
I need to write a method to create an array from text, delete duplicates and return an array of the words which are used only once and don't have duplicates.
I can't find out how to make a new array of unique words. Using only simple and basic construction without HashSet etc.*
For example:
a b a b c a b d
result:
c d
public static String Dublicate(String text) {
String[] dublic = text.split(" ");
String result="";
for (int i = 0; i < dublic.length; i++) {
for (int j = i + 1; j < dublic.length; j++)
if (dublic[i].equals(dublic[j]))
dublic[j] = "delete";
}
for (String s: dublic) {
if (s !="delete") {
result =result + s + " ";
}
}
return result;
}
Split By Space
For splitting by space we can use the split() method & can pass the Space string ("") in the parameter.
String[] texts = text.split(" ");
Delete The duplicate elements
If We can use java 1.8 or greater than 1.8, we can use stream API for getting distinct elements like.
Arrays.stream(texts).distinct().toArray(String[]::new);
Or if we need to implement it with java 1.7, we can use HashSet for getting distinct elements like.
String[] distinctElements = new HashSet<String>(Arrays.asList(texts)).toArray(new String[0]);
The final Source code can be like this:
public static String[] textToArray1_7(String text) {
//split by space
String[] texts = text.split(" ");
//Distinct value
return Arrays.stream(texts).distinct().toArray(String[]::new);
}
public static String[] textToArray1_8(String text) {
//split by space
String[] texts = text.split(" ");
//Distinct value
return new HashSet<String>(Arrays.asList(texts)).toArray(new String[0]);
}
If any further question, can ask for more clarification.
You forgot to mark i-th element as duplicate in case when it really is. See my comments in the below code
public static String Dublicate(String text) {
String[] dublic = text.split(" ");
String result="";
for (int i=0; i<dublic.length; i++){
if (dublic[i].equals("delete")) { // Minor optimization:
// skip elements that are already marked
continue;
}
boolean isDub = false; // we need to track i-th element
for(int j=i+1; j<dublic.length; j++) {
if (dublic[i].equals(dublic[j])) {
dublic[j] = "delete";
isDub = true; // i-th element is also a duplicate...
}
}
if (isDub) {
dublic[i] = "delete"; // ...so you should also mark it
}
}
for(String s: dublic){
if(!s.equals("delete")) { // for strings you should use "!equals" instead of "!="
result = result + s + " ";
}
}
return result;
}
P.S. if original text contains "delete" the result will be incorrect since you use "delete" as a reserved marker word
If the array of unique strings needs to be returned, then the initial array of strings after the splitting the input has to be compacted to exclude invalid values, and a smaller copy needs to be returned:
public static String[] uniques(String text) {
String[] words = text.split(" ");
int p = 0; // index/counter of unique elements
for (int i = 0; i < words.length; i++) {
String curr = words[i];
if (null == curr) {
continue;
}
boolean dupFound = false;
for (int j = i + 1; j < words.length; j++) {
if (null == words[j]) {
continue;
}
if (curr.equals(words[j])) {
words[j] = null;
dupFound = true;
}
}
if (dupFound) {
words[i] = null;
} else {
words[p++] = words[i]; // shift unique elements to the start of array
}
}
return Arrays.copyOf(words, p);
}
If the array of unique strings is returned, it may be conveniently converted into String using String::join as shown below in the test.
Test:
System.out.println(Arrays.toString(uniques("a b a b c a b d")));
System.out.println(String.join(" ", uniques("a b a b c a b d")));
Output
[c, d]
c d

Converting int array to String and returning (getArrayString)

I have to make a getArrayString(int[] array, char separator) method which return a string where each array entry (except the last one) is followed by the specified separator.
I know the structor of the arrays methods but in this one first I have to fined a formula for returning array except the last one and second convert my int[] array to String and return it with separator.
public static getArrayString(int[] array, char separator) {
if(array == null ||array.length == 0) {
return null;
}
int size =0;
for(int i =0; i < array.length; i++) {
size++;
}
int[] newArray2 = new int[size];
for(int i= 0, position = 0; i < array.length; i++) {
newArray2[position]=i;
position++;
System.out.print(i+',');
}
// String StArray = Arrays.toString(newArray2);
// return StArray + separator;
// newArray2 = convertStringArrayToString(StArray,separator);
// return StArray;
//
//return Arrays.toString(newArray2)+ separator;
}
// private static String convertStringArrayToString(String[] newArray,char separator) {
// StringBuilder sb = new StringBuilder();
// for(String StArray : newArray);
// return sb.substring(0,sb.length()-1);
// }
The comments are ideas of converting to String and returning it!
Joining int[] to a String
Edit: I just spotted you have an int[] not a String[]. I would probably use the Streams approach:
String result = Arrays.stream(array)
.mapToObj(String::valueOf)
.collect(Collectors.joining(separator));
If you really want to use a for-loop, you should use a StringJoiner:
public static getArrayString(int[] array, char separator) {
if(array == null || array.length == 0) return "";
String separatorString = String.valueOf(separator);
StringJoiner sj = new StringJoiner(separatorString);
for(int element : array) {
sj.add(String.valueOf(element));
}
return sj.toString();
}
Joining String[] to a String
The phrasing of your question makes me think you're studying this for a class, but if you're not, just use the in-built join
function:
// join takes Iterable<? extends CharSequence> or vararg
String.join(separator, myArray)
String.join(separator, myList)
String.join(separator, charSeq1, charSeq2, ..., charSeqN)
If you need prefix/suffix, you can use a StringJoiner:
StringJoiner sj = new StringJoiner(separator, prefix, suffix);
String result = sj.add(s1).add(s2).add(s3).toString();
...which is also the basis of the Stream Collectors.joining:
String result = Arrays.stream(array)
.collect(Collectors.joining(separator));
String result = Arrays.stream(array)
.collect(Collectors.joining(separator, prefix, suffix));
public static String getArrayString(int[] array, char separator) {
if(array == null || array.length == 0) {
return null;
}
String str = "";
for(int i = 0; i < array.length-1; i++) {
str += "" + array[i]+ separator;
}
// add the last one
str += array[array.length - 1];
return str;
}

Java parse String containing integers and multiple delimiters

Here is an example String, which contains 2 delimiters used for parsing the String to integers:
"1,25,3-6,14,16-19"
The integers in the aforementioned string have to be parsed and added to ArrayList cotaining integers. So the ArrayList has to contain:
1,3,4,5,6,14,16,17,18,19,25
The values in the original string are never mentioned twice. So, there are no crossing sections. Below you can see the incomplete code I wrote so far, but I think that I'm going in a completely wrong direction and there should be an easier way to solve the parsing.
List<Integer> temp = new ArrayList<>();
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char[] strCh = str.toCharArray();
for (int j = 0; j < strCh.length; j++) {
char c = strCh[j];
String number = "";
char operator = 'n';
if (Character.isDigit(c)) {
do {
number += c;
j++;
if (j != strCh.length - 1)
c = strCh[j];
} while (j < strCh.length && Character.isDigit(c));
} else if (c == ',') {
operator = ',';
temp.add(Integer.parseInt(number));
number = "";
} else if (c == '-') {
//still not sure
}
}
You can use String#split() twice to handle your input string. First split by comma, which leaves us with either an individual number, or an individual range of numbers. Then, in the case of range, split again by dash to obtain the starting and ending numbers of that range. We can iterate over that range, adding each number to our list.
String input = "1,25,3-6,14,16-19";
String[] parts = input.split(",");
List<Integer> list = new ArrayList<>();
for (String part : parts) {
if (part.contains("-")) {
String[] range = part.split("-");
int start = Integer.parseInt(range[0]);
int end = Integer.parseInt(range[1]);
for (int i=start; i <= end; ++i) {
list.add(i);
}
}
else {
int value = Integer.parseInt(part);
list.add(value);
}
}
This generated the following list of numbers:
1,25,3,4,5,6,14,16,17,18,19
Demo here:
Rextester
To ensure there are no duplicates and in order as you expect, use Set:
String inputData = "1,25,3-6,14,16-19";
String[] numberRanges = inputData.split(",");
Set<Integer> set = new TreeSet<>();
for (String numberRange : numberRanges) {
if (numberRange.contains("-")) {
String[] range = numberRange.split("-");
int startIndex = Integer.valueOf(range[0]);
int endIndex = Integer.valueOf(range[1]);
for (int i = startIndex; i <= endIndex; ++i) {
set.add(i);
}
} else {
set.add(Integer.valueOf(numberRange));
}
}
System.out.println(set);
You can try something like this:
String input = "1,25,3-6,14,16-19";
List<Integer> output = new ArrayList<Integer>();
for(String s : input.split(",")){
try{
if(!s.contains("-")){
output.add(Integer.parseInt(s));
}
else{
int i= Integer.parseInt(s.split("-")[0]);
int upperBound = Integer.parseInt(s.split("-")[1]);
for(;i<=upperBound;i++){
output.add(i);
}
}
}catch(NumberFormatException e){
e.printStackTrace();
}
}
Collections.sort(output); // sort the result
System.out.println(output); // test
Output
[1, 3, 4, 5, 14, 16, 17, 18, 19, 25]
Take a look at the StringTokenizer.

How to shift each elements in array using loops?

I want to shift each elements in array to left if there is a null. E.g
public static void main(String[] args) {
String asd[] = new String[5];
asd[0] = "zero";
asd[1] = "one";
asd[2] = null;
asd[3] = "three";
asd[4] = "four;
I want the output to be
zero, one, three, four.
The length should also be adjusted
How can i do this using loops? I tried using if statements to check if an element is not null copy that value to another array. But i dont know how to copy if there is a null.
Given the kind of question, I suppose you want a simple, loop only and array only based solution, to understand how it works.
You have to iterate on the array, keeping an index of the new insertion point. At the end, using that same index, you can "shrink" the array (actually copy to a new smaller array).
String[] arr = {"a","b",null,"c",null,"d"};
// This will move all elements "up" when nulls are found
int p = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == null) continue;
arr[p] = arr[i];
p++;
}
// This will copy to a new smaller array
String[] newArr = new String[p];
System.arraycopy(arr,0,newArr,0,p);
Just tested this code.
EDIT :
Regarding the possibility of shrinking the array without using System.arraycopy, unfortunately in Java arrays size must be declared when they are instantiated, and can't be changed (nor made bigger nor smaller) after.
So if you have an array of length 6, and find 2 nulls, you have no way of shrinking it to a length of 4, if not creating a new empty array and then copying elements.
Lists can grow and shrink, and are more handy to use. For example, the same code with a list would be :
String[] arr = {"a","b",null,"c",null,"d"};
List<String> list = new ArrayList<>(Arrays.asList(arr));
Iterator<String> iter = list.iterator();
while (iter.hasNext()) if (iter.next() == null) iter.remove();
System.out.println(list);
Try:
int lengthNoNull = 0;
for(String a : asd) {
if(a != null) {
lengthNoNull++;
}
}
String[] newAsd = new String[lengthNoNull];
int i = 0;
for(String a : asd) {
if(a != null) {
newAsd[i++] = a;
}
}
Piece of code using only arrays.
String[] x = {"1","2","3",null,"4","5","6",null,"7","8","9"};
String[] a = new String[x.length];
int i = 0;
for(String s : x) {
if(s != null) a[i++] = s;
}
String[] arr = Arrays.copyOf(a, i);
Or this:
String[] xx = {"1","2","3",null,"4","5","6",null,"7","8","9"};
int pos = 0, i = 0;
String tmp;
for(String s : xx) {
if(s == null) {
tmp = xx[pos];
xx[pos] = s;
xx[i] = tmp;
pos++;
}
i++;
}
String[] arr = Arrays.copyOfRange(xx, pos, xx.length);

function to remove duplicate characters in a string

The following code is trying to remove any duplicate characters in a string. I'm not sure if the code is right. Can anybody help me work with the code (i.e whats actually happening when there is a match in characters)?
public static void removeDuplicates(char[] str) {
if (str == null) return;
int len = str.length;
if (len < 2) return;
int tail = 1;
for (int i = 1; i < len; ++i) {
int j;
for (j = 0; j < tail; ++j) {
if (str[i] == str[j]) break;
}
if (j == tail) {
str[tail] = str[i];
++tail;
}
}
str[tail] = 0;
}
The function looks fine to me. I've written inline comments. Hope it helps:
// function takes a char array as input.
// modifies it to remove duplicates and adds a 0 to mark the end
// of the unique chars in the array.
public static void removeDuplicates(char[] str) {
if (str == null) return; // if the array does not exist..nothing to do return.
int len = str.length; // get the array length.
if (len < 2) return; // if its less than 2..can't have duplicates..return.
int tail = 1; // number of unique char in the array.
// start at 2nd char and go till the end of the array.
for (int i = 1; i < len; ++i) {
int j;
// for every char in outer loop check if that char is already seen.
// char in [0,tail) are all unique.
for (j = 0; j < tail; ++j) {
if (str[i] == str[j]) break; // break if we find duplicate.
}
// if j reachs tail..we did not break, which implies this char at pos i
// is not a duplicate. So we need to add it our "unique char list"
// we add it to the end, that is at pos tail.
if (j == tail) {
str[tail] = str[i]; // add
++tail; // increment tail...[0,tail) is still "unique char list"
}
}
str[tail] = 0; // add a 0 at the end to mark the end of the unique char.
}
Your code is, I'm sorry to say, very C-like.
A Java String is not a char[]. You say you want to remove duplicates from a String, but you take a char[] instead.
Is this char[] \0-terminated? Doesn't look like it because you take the whole .length of the array. But then your algorithm tries to \0-terminate a portion of the array. What happens if the arrays contains no duplicates?
Well, as it is written, your code actually throws an ArrayIndexOutOfBoundsException on the last line! There is no room for the \0 because all slots are used up!
You can add a check not to add \0 in this exceptional case, but then how are you planning to use this code anyway? Are you planning to have a strlen-like function to find the first \0 in the array? And what happens if there isn't any? (due to all-unique exceptional case above?).
What happens if the original String/char[] contains a \0? (which is perfectly legal in Java, by the way, see JLS 10.9 An Array of Characters is Not a String)
The result will be a mess, and all because you want to do everything C-like, and in place without any additional buffer. Are you sure you really need to do this? Why not work with String, indexOf, lastIndexOf, replace, and all the higher-level API of String? Is it provably too slow, or do you only suspect that it is?
"Premature optimization is the root of all evils". I'm sorry but if you can't even understand what the original code does, then figuring out how it will fit in the bigger (and messier) system will be a nightmare.
My minimal suggestion is to do the following:
Make the function takes and returns a String, i.e. public static String removeDuplicates(String in)
Internally, works with char[] str = in.toCharArray();
Replace the last line by return new String(str, 0, tail);
This does use additional buffers, but at least the interface to the rest of the system is much cleaner.
Alternatively, you can use StringBuilder as such:
static String removeDuplicates(String s) {
StringBuilder noDupes = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
String si = s.substring(i, i + 1);
if (noDupes.indexOf(si) == -1) {
noDupes.append(si);
}
}
return noDupes.toString();
}
Note that this is essentially the same algorithm as what you had, but much cleaner and without as many little corner cases, etc.
Given the following question :
Write code to remove the duplicate characters in a string without
using any additional buffer. NOTE: One or two additional variables
are fine. An extra copy of the array is not.
Since one or two additional variables are fine but no buffer is allowed, you can simulate the behaviour of a hashmap by using an integer to store bits instead. This simple solution runs at O(n), which is faster than yours. Also, it isn't conceptually complicated and in-place :
public static void removeDuplicates(char[] str) {
int map = 0;
for (int i = 0; i < str.length; i++) {
if ((map & (1 << (str[i] - 'a'))) > 0) // duplicate detected
str[i] = 0;
else // add unique char as a bit '1' to the map
map |= 1 << (str[i] - 'a');
}
}
The drawback is that the duplicates (which are replaced with 0's) will not be placed at the end of the str[] array. However, this can easily be fixed by looping through the array one last time. Also, an integer has the capacity for only regular letters.
private static String removeDuplicateCharactersFromWord(String word) {
String result = new String("");
for (int i = 0; i < word.length(); i++) {
if (!result.contains("" + word.charAt(i))) {
result += "" + word.charAt(i);
}
}
return result;
}
This is my solution.
The algorithm is mainly the same as the one in the book "Cracking the code interview" where this exercise comes from, but I tried to improve it a bit and make the code more understandable:
public static void removeDuplicates(char[] str) {
// if string has less than 2 characters, it can't contain
// duplicate values, so there's nothing to do
if (str == null || str.length < 2) {
return;
}
// variable which indicates the end of the part of the string
// which is 'cleaned' (all duplicates removed)
int tail = 0;
for (int i = 0; i < str.length; i++) {
boolean found = false;
// check if character is already present in
// the part of the array before the current char
for (int j = 0; j < i; j++) {
if (str[j] == str[i]) {
found = true;
break;
}
}
// if char is already present
// skip this one and do not copy it
if (found) {
continue;
}
// copy the current char to the index
// after the last known unique char in the array
str[tail] = str[i];
tail++;
}
str[tail] = '\0';
}
One of the important requirements from the book is to do it in-place (as in my solution), which means that no additional data structure should be used as a helper while processing the string. This improves performance by not wasting memory unnecessarily.
char[] chars = s.toCharArray();
HashSet<Character> charz = new HashSet<Character>();
for(Character c : s.toCharArray() )
{
if(!charz.contains(c))
{
charz.add(c);
//System.out.print(c);
}
}
for(Character c : charz)
{
System.out.print(c);
}
public String removeDuplicateChar(String nonUniqueString) {
String uniqueString = "";
for (char currentChar : nonUniqueString.toCharArray()) {
if (!uniqueString.contains("" + currentChar)) {
uniqueString += currentChar;
}
}
return uniqueString;
}
public static void main (String [] args)
{
String s = "aabbbeeddsfre";//sample string
String temp2="";//string with no duplicates
HashMap<Integer,Character> tc = new HashMap<Integer,Character>();//create a hashmap to store the char's
char [] charArray = s.toCharArray();
for (Character c : charArray)//for each char
{
if (!tc.containsValue(c))//if the char is not already in the hashmap
{
temp2=temp2+c.toString();//add the char to the output string
tc.put(c.hashCode(),c);//and add the char to the hashmap
}
}
System.out.println(temp2);//final string
}
instead of HashMap I think we can use Set too.
I understand that this is a Java question, but since I have a nice solution which could inspire someone to convert this into Java, by all means. Also I like answers where multiple language submissions are available to common problems.
So here is a Python solution which is O(n) and also supports the whole ASCII range. Of course it does not treat 'a' and 'A' as the same:
I am using 8 x 32 bits as the hashmap:
Also input is a string array using dedup(list('some string'))
def dedup(str):
map = [0,0,0,0,0,0,0,0]
for i in range(len(str)):
ascii = ord(str[i])
slot = ascii / 32
bit = ascii % 32
bitOn = map[slot] & (1 << bit)
if bitOn:
str[i] = ''
else:
map[slot] |= 1 << bit
return ''.join(str)
also a more pythonian way to do this is by using a set:
def dedup(s):
return ''.join(list(set(s)))
Substringing method. Concatenation is done with .concat() to avoid allocation additional memory for left hand and right hand of +.
Note: This removes even duplicate spaces.
private static String withoutDuplicatesSubstringing(String s){
for(int i = 0; i < s.length(); i++){
String sub = s.substring(i+1);
int index = -1;
while((index = sub.toLowerCase().indexOf(Character.toLowerCase(s.charAt(i)))) > -1 && !sub.isEmpty()){
sub = sub.substring(0, index).concat(sub.substring(index+1, sub.length()));
}
s = s.substring(0, i+1).concat(sub);
}
return s;
}
Test case:
String testCase1 = "nanananaa! baaaaatmaan! batman!";
Output:
na! btm
Question: Remove Duplicate characters in a string
Method 1 :(Python)
import collections
a = "GiniGinaProtijayi"
aa = collections.OrderedDict().fromkeys(a)
print(''.join(aa))
Method 2 :(Python)
a = "GiniGinaProtijayi"
list = []
aa = [ list.append(ch) for ch in a if ch not in list]
print( ''.join(list))
IN Java:
class test2{
public static void main(String[] args) {
String a = "GiniGinaProtijayi";
List<Character> list = new ArrayList<>();
for(int i = 0 ; i < a.length() ;i++) {
char ch = a.charAt(i);
if( list.size() == 0 ) {list.add(ch);}
if(!list.contains(ch)) {list.add(ch) ;}
}//for
StringBuffer sbr = new StringBuffer();
for( char ch : list) {sbr.append(ch);}
System.out.println(sbr);
}//main
}//end
This would be much easier if you just looped through the array and added all new characters to a list, then retruned that list.
With this approach, you need to reshuffle the array as you step through it and eventually redimension it to the appropriate size in the end.
String s = "Javajk";
List<Character> charz = new ArrayList<Character>();
for (Character c : s.toCharArray()) {
if (!(charz.contains(Character.toUpperCase(c)) || charz
.contains(Character.toLowerCase(c)))) {
charz.add(c);
}
}
ListIterator litr = charz.listIterator();
while (litr.hasNext()) {
Object element = litr.next();
System.err.println(":" + element);
} }
this will remove the duplicate if the character present in both the case.
public class RemoveDuplicateInString {
public static void main(String[] args) {
String s = "ABCDDCA";
RemoveDuplicateInString rs = new RemoveDuplicateInString();
System.out.println(rs.removeDuplicate(s));
}
public String removeDuplicate(String s) {
String retn = null;
boolean[] b = new boolean[256];
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (b[ch[i]]) {
ch[i]=' ';
}
else {
b[ch[i]] = true;
}
}
retn = new String(ch);
return retn;
}
}
/* program to remove the duplicate character in string */
/* Author senthilkumar M*/
char *dup_remove(char *str)
{
int i = 0, j = 0, l = strlen(str);
int flag = 0, result = 0;
for(i = 0; i < l; i++) {
result = str[i] - 'a';
if(flag & (1 << result)) {
*/* if duplicate found remove & shift the array*/*
for(j = i; j < l; j++) {
str[j] = str[j+1];
}
i--;
l--; /* duplicates removed so string length reduced by 1 character*/
continue;
}
flag |= (1 << result);
}
return str;
}
public class RemoveCharsFromString {
static String testcase1 = "No, I am going to Noida";
static String testcase2 = "goings";
public static void main(String args[])throws StringIndexOutOfBoundsException{
RemoveCharsFromString testInstance= new RemoveCharsFromString();
String result = testInstance.remove(testcase1,testcase2);
System.out.println(result);
}
//write your code here
public String remove(String str, String str1)throws StringIndexOutOfBoundsException
{ String result=null;
if (str == null)
return "";
try
{
for (int i = 0; i < str1.length (); i++)
{
char ch1=str1.charAt(i);
for(int j=0;j<str.length();j++)
{
char ch = str.charAt (j);
if (ch == ch1)
{
String s4=String.valueOf(ch);
String s5= str.replaceAll(s4, "");
str=s5;
}
}
}
}
catch(Exception e)
{
}
result=str;
return result;
}
}
public static void main(String[] args) {
char[] str = { 'a', 'b', 'a','b','c','e','c' };
for (int i = 1; i < str.length; i++) {
for (int j = 0; j < i; j++) {
if (str[i] == str[j]) {
str[i] = ' ';
}
}
}
System.out.println(str);
}
An improved version for using bitmask to handle 256 chars:
public static void removeDuplicates3(char[] str)
{
long map[] = new long[] {0, 0, 0 ,0};
long one = 1;
for (int i = 0; i < str.length; i++)
{
long chBit = (one << (str[i]%64));
int n = (int) str[i]/64;
if ((map[n] & chBit ) > 0) // duplicate detected
str[i] = 0;
else // add unique char as a bit '1' to the map
map[n] |= chBit ;
}
// get rid of those '\0's
int wi = 1;
for (int i=1; i<str.length; i++)
{
if (str[i]!=0) str[wi++] = str[i];
}
// setting the rest as '\0'
for (;wi<str.length; wi++) str[wi] = 0;
}
Result: "##1!!ASDJasanwAaw.,;..][,[]==--0" ==> "#1!ASDJasnw.,;][=-0" (double quotes not included)
This function removes duplicate from string inline. I have used C# as a coding language and the duplicates are removed inline
public static void removeDuplicate(char[] inpStr)
{
if (inpStr == null) return;
if (inpStr.Length < 2) return;
for (int i = 0; i < inpStr.Length; ++i)
{
int j, k;
for (j = 1; j < inpStr.Length; j++)
{
if (inpStr[i] == inpStr[j] && i != j)
{
for (k = j; k < inpStr.Length - 1; k++)
{
inpStr[k] = inpStr[k + 1];
}
inpStr[k] = ' ';
}
}
}
Console.WriteLine(inpStr);
}
(Java) Avoiding usage of Map, List data structures:
private String getUniqueStr(String someStr) {
StringBuilder uniqueStr = new StringBuilder();
if(someStr != null) {
for(int i=0; i <someStr.length(); i++) {
if(uniqueStr.indexOf(String.valueOf(someStr.charAt(i))) == -1) {
uniqueStr.append(someStr.charAt(i));
}
}
}
return uniqueStr.toString();
}
package com.java.exercise;
public class RemoveCharacter {
/**
* #param args
*/
public static void main(String[] args) {
RemoveCharacter rem = new RemoveCharacter();
char[] ch=rem.GetDuplicates("JavavNNNNNNC".toCharArray());
char[] desiredString="JavavNNNNNNC".toCharArray();
System.out.println(rem.RemoveDuplicates(desiredString, ch));
}
char[] GetDuplicates(char[] input)
{
int ctr=0;
char[] charDupl=new char[20];
for (int i = 0; i <input.length; i++)
{
char tem=input[i];
for (int j= 0; j < i; j++)
{
if (tem == input[j])
{
charDupl[ctr++] = input[j];
}
}
}
return charDupl;
}
public char[] RemoveDuplicates(char[] input1, char []input2)
{
int coutn =0;
char[] out2 = new char[10];
boolean flag = false;
for (int i = 0; i < input1.length; i++)
{
for (int j = 0; j < input2.length; j++)
{
if (input1[i] == input2[j])
{
flag = false;
break;
}
else
{
flag = true;
}
}
if (flag)
{
out2[coutn++]=input1[i];
flag = false;
}
}
return out2;
}
}
Yet another solution, seems to be the most concise so far:
private static String removeDuplicates(String s)
{
String x = new String(s);
for(int i=0;i<x.length()-1;i++)
x = x.substring(0,i+1) + (x.substring(i+1)).replace(String.valueOf(x.charAt(i)), "");
return x;
}
I have written a piece of code to solve the problem.
I have checked with certain values, got the required output.
Note: It's time consuming.
static void removeDuplicate(String s) {
char s1[] = s.toCharArray();
Arrays.sort(s1); //Sorting is performed, a to z
//Since adjacent values are compared
int myLength = s1.length; //Length of the character array is stored here
int i = 0; //i refers to the position of original char array
int j = 0; //j refers to the position of char array after skipping the duplicate values
while(i != myLength-1 ){
if(s1[i]!=s1[i+1]){ //Compares two adjacent characters, if they are not the same
s1[j] = s1[i]; //if not same, then, first adjacent character is stored in s[j]
s1[j+1] = s1[i+1]; //Second adjacent character is stored in s[j+1]
j++; //j is incremented to move to next location
}
i++; //i is incremented
}
//the length of s is i. i>j
String s4 = new String (s1); //Char Array to String
//s4[0] to s4[j+1] contains the length characters after removing the duplicate
//s4[j+2] to s4[i] contains the last set of characters of the original char array
System.out.println(s4.substring(0, j+1));
}
Feel free to run my code with your inputs. Thanks.
public class RemoveRepeatedCharacters {
/**
* This method removes duplicates in a given string in one single pass.
* Keeping two indexes, go through all the elements and as long as subsequent characters match, keep
* moving the indexes in opposite directions. When subsequent characters don't match, copy value at higher index
* to (lower + 1) index.
* Time Complexity = O(n)
* Space = O(1)
*
*/
public static void removeDuplicateChars(String text) {
char[] ch = text.toCharArray();
int i = 0; //first index
for(int j = 1; j < ch.length; j++) {
while(i >= 0 && j < ch.length && ch[i] == ch[j]) {
i--;
j++;
System.out.println("i = " + i + " j = " + j);
}
if(j < ch.length) {
ch[++i] = ch[j];
}
}
//Print the final string
for(int k = 0; k <= i; k++)
System.out.print(ch[k]);
}
public static void main(String[] args) {
String text = "abccbdeefgg";
removeDuplicateChars(text);
}
}
public class StringRedundantChars {
/**
* #param args
*/
public static void main(String[] args) {
//initializing the string to be sorted
String sent = "I love painting and badminton";
//Translating the sentence into an array of characters
char[] chars = sent.toCharArray();
System.out.println("Before Sorting");
showLetters(chars);
//Sorting the characters based on the ASCI character code.
java.util.Arrays.sort(chars);
System.out.println("Post Sorting");
showLetters(chars);
System.out.println("Removing Duplicates");
stripDuplicateLetters(chars);
System.out.println("Post Removing Duplicates");
//Sorting to collect all unique characters
java.util.Arrays.sort(chars);
showLetters(chars);
}
/**
* This function prints all valid characters in a given array, except empty values
*
* #param chars Input set of characters to be displayed
*/
private static void showLetters(char[] chars) {
int i = 0;
//The following loop is to ignore all white spaces
while ('\0' == chars[i]) {
i++;
}
for (; i < chars.length; i++) {
System.out.print(" " + chars[i]);
}
System.out.println();
}
private static char[] stripDuplicateLetters(char[] chars) {
// Basic cursor that is used to traverse through the unique-characters
int cursor = 0;
// Probe which is used to traverse the string for redundant characters
int probe = 1;
for (; cursor < chars.length - 1;) {
// Checking if the cursor and probe indices contain the same
// characters
if (chars[cursor] == chars[probe]) {
System.out.println("Removing char : " + chars[probe]);
// Please feel free to replace the redundant character with
// character. I have used '\0'
chars[probe] = '\0';
// Pushing the probe to the next character
probe++;
} else {
// Since the probe has traversed the chars from cursor it means
// that there were no unique characters till probe.
// Hence set cursor to the probe value
cursor = probe;
// Push the probe to refer to the next character
probe++;
}
}
System.out.println();
return chars;
}
}
This is my solution
public static String removeDup(String inputString){
if (inputString.length()<2) return inputString;
if (inputString==null) return null;
char[] inputBuffer=inputString.toCharArray();
for (int i=0;i<inputBuffer.length;i++){
for (int j=i+1;j<inputBuffer.length;j++){
if (inputBuffer[i]==inputBuffer[j]){
inputBuffer[j]=0;
}
}
}
String result=new String(inputBuffer);
return result;
}
Well I came up with the following solution.
Keeping in mind that S and s are not duplicates. Also I have just one hard coded value.. But the code works absolutely fine.
public static String removeDuplicate(String str)
{
StringBuffer rev = new StringBuffer();
rev.append(str.charAt(0));
for(int i=0; i< str.length(); i++)
{
int flag = 0;
for(int j=0; j < rev.length(); j++)
{
if(str.charAt(i) == rev.charAt(j))
{
flag = 0;
break;
}
else
{
flag = 1;
}
}
if(flag == 1)
{
rev.append(str.charAt(i));
}
}
return rev.toString();
}
I couldn't understand the logic behind the solution so I wrote my simple solution:
public static void removeDuplicates(char[] str) {
if (str == null) return; //If the string is null return
int length = str.length; //Getting the length of the string
if (length < 2) return; //Return if the length is 1 or smaller
for(int i=0; i<length; i++){ //Loop through letters on the array
int j;
for(j=i+1;j<length;j++){ //Loop through letters after the checked letters (i)
if (str[j]==str[i]){ //If you find duplicates set it to 0
str[j]=0;
}
}
}
}
Using guava you can just do something like Sets.newHashSet(charArray).toArray();
If you are not using any libraries, you can still use new HashSet<Char>() and add your char array there.
#include <iostream>
#include <string>
using namespace std;
int main() {
// your code goes here
string str;
cin >> str;
long map = 0;
for(int i =0; i < str.length() ; i++){
if((map & (1L << str[i])) > 0){
str[i] = 0;
}
else{
map |= 1L << str[i];
}
}
cout << str;
return 0;
}

Categories