Tuesday 23 March 2021

Published March 23, 2021 by with 0 comment

Removing duplicate characters from given string without using Java Built in functions.

Approch 1

First will convert String to Characters by using toCharArray function. After that will store that CharArray to Set it will automatically remove all duplicates. And then will use StringBuilder function to reconstruct that String.


Code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package javaProgramsforInterview;
 
import java.util.LinkedHashSet;
import java.util.Set;
 
public class RemovingDuplicates1 {
 
	public static void main(String[] args) {
		String string = "samplestringfortest";
 
		char[] chars = string.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);
		}
		System.out.println(sb.toString());
	}
}
Output:

sampletringfo


Approch 2

First will convert String to Characters by using toCharArray function. After that we will compare n’th letter from zero to (n-1) index to all the letters of string. Then we will use a boolean flag to check the duplicate letter. If a duplicate letter is found then will turn off the flag and will not append the letter to the String. If there is no duplicate letter then we will keep the flag value as true and will append the letter to string. For string reconstruction we are using StringBuilder function.


Code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package javaProgramsforInterview;
 
public class RemovingDuplicates2 {. 
 
	public static void main(String[] args) {
		String string = "samplestringfortest";
		char[] chars = string.toCharArray();
		StringBuilder sb1 = new StringBuilder();
 
		for (int i = 0; i < chars.length; i++) {
			boolean flag = true;
			for (int j = 0; j < i; j++) {
				if (chars[j] == chars[i]) {
					flag = false;
					break;
				}
			}
			if (flag) {
				sb1.append(chars[i]);
			}
		}
		System.out.println(sb1.toString());
	}
}
Output:

sampletringfo

0 comments:

Post a Comment