How to remove duplicate alphabets from two strings in java without any builtin functions?
Here is one approach,
// Write a static helper method.
public static boolean contains(char[] in, int index, char t) {
for (int i = 0; i < index; i++) {
if (in[i] == t) return true;
}
return false;
}
public static void main(String[] args) {
String firstString = "google out"; // String(s) not String arrays
String secondString = "stack overflow";
// output cannot be larger then the sum of the inputs.
char[] out = new char[firstString.length() + secondString.length()];
int index = 0;
// Add all unique chars from firstString
for (char c : firstString.toCharArray()) {
if (! contains(out, index, c)) {
out[index++] = c;
}
}
// Add all unique chars from secondString
for (char c : secondString.toCharArray()) {
if (! contains(out, index, c)) {
out[index++] = c;
}
}
// Create a correctly sized output array.
char[] s = new char[index];
for (int i = 0; i < index; i++) {
s[i] = out[i];
}
// Just print it.
System.out.println(Arrays.toString(s));
}
Output is
[g, o, l, e, , u, t, s, a, c, k, v, r, f, w]
Edit
If your expected output is incorrect, and you actually want the characters that appear in both Strings.
public static void main(String[] args) {
String firstString = "google out";
String secondString = "stack overflow";
char[] out = new char[firstString.length() + secondString.length()];
int index = 0;
for (char c : firstString.toCharArray()) {
if (contains(secondString.toCharArray(), secondString.length(), c)) {
out[index++] = c;
}
}
char[] s = new char[index];
for (int i = 0; i < index; i++) {
s[i] = out[i];
}
System.out.println(Arrays.toString(s));
}
Which outputs
[o, o, l, e, , o, t]
Edit 2
If you actually wanted the opposite of that, change the call to contains
and add a second loop (for the inverse relationship) -
for (char c : firstString.toCharArray()) {
if (! contains(secondString.toCharArray(), secondString.length(), c)) {
out[index++] = c;
}
}
for (char c : secondString.toCharArray()) {
if (! contains(firstString.toCharArray(), firstString.length(), c)) {
out[index++] = c;
}
}
Which will then output
[g, g, u, s, a, c, k, v, r, f, w]
Removing duplicates from a String in Java
Convert the string to an array of char, and store it in a LinkedHashSet
. That will preserve your ordering, and remove duplicates. Something like:
String string = "aabbccdefatafaz";
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());
How to count common characters in two strings in JavaScript?
We can convert the second input string to an array, then the next step is to iterate over the first input string and find a match in the second input string's character array.
If a match is found, increment the counter and remove that character from the second input string's character array so that it is not considered in the next match:
//Solution:function getSameCount(str1, str2) { let count = 0; const obj = str2.split(""); for(str of str1){ let idx = obj.findIndex(s => s === str); if(idx >= 0){ count++; obj.splice(idx, 1); } } return count;}
//Test:console.log(getSameCount("abcd", "aad"));console.log(getSameCount("geeksforgeeks", "platformforgeeks"));console.log(getSameCount("aad", "abcd"));console.log(getSameCount("platformforgeeks", "geeksforgeeks"));
Java: removing numeric values from string
Your regular expression [^A-Z]
is currently only configured to preserve upper-case letters. You could try replacing it with [^A-Za-z]
to keep the lower-case letters too.
How to remove single character from a String
You can also use the StringBuilder
class which is mutable.
StringBuilder sb = new StringBuilder(inputString);
It has the method deleteCharAt()
, along with many other mutator methods.
Just delete the characters that you need to delete and then get the result as follows:
String resultString = sb.toString();
This avoids creation of unnecessary string objects.
How to remove the last character from a string?
replace
will replace all instances of a letter. All you need to do is use substring()
:
public String method(String str) {
if (str != null && str.length() > 0 && str.charAt(str.length() - 1) == 'x') {
str = str.substring(0, str.length() - 1);
}
return str;
}
Java String remove all non numeric characters but keep the decimal separator
Try this code:
String str = "a12.334tyz.78x";
str = str.replaceAll("[^\\d.]", "");
Now str
will contain "12.334.78"
.
Related Topics
Regular Expression to Validate Username
Java Simpledateformatter With 10 Decimals After the Seconds, Cannot Convert to Date
How to Return a Custom Object from a Spring Data JPA Group by Query
Automatically Convert Style Sheets to Inline Style
Http Post Request With Content Type Application/X-Www-Form-Urlencoded Not Working in Spring
How to Get Row Count Using Resultset in Java
Java Error Message. Unexpected Type, Required Variable, Found Value
When I Run Mockito Test Occurs Wrongtypeofreturnvalue Exception
Mailconnectexception: Couldn't Connect to Host, Port: Smtp.Sendgrid.Net
How to Extract Ip Address in Spring MVC Controller Get Call
Notifydatasetchanged() Makes the List Refresh and Scroll Jumps Back to the Top
Java.Io.Filenotfoundexception: the System Cannot Find the File Specified
How to Get a Resource Id With a Known Resource Name
Delete Not Working in Hibernate/Spring Data
Using Nested While Loop to Print Pyramid of Stars
Way to Check If Two Collections Contain the Same Elements, Independent of Order
Spring Jpa/Hibernate Transaction Force Insert Instead of Update