I am trying to iterate through a string in order to remove the duplicates characters.
For example the String aabbccdef should become abcdef
and the String abcdabcd should become abcd
Here is what I have so far:
public class test {
public static void main(String[] args) {
String input = new String("abbc");
String output = new String();
for (int i = 0; i < input.length(); i++) {
for (int j = 0; j < output.length(); j++) {
if (input.charAt(i) != output.charAt(j)) {
output = output + input.charAt(i);
}
}
}
System.out.println(output);
}
}
What is the best way to do this?
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());
Using Stream makes it easy.
noDuplicates = Arrays.asList(myString.split(""))
.stream()
.distinct()
.collect(Collectors.joining());
Here is some more documentation about Stream and all you can do with
it :
https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html
The 'description' part is very instructive about the benefits of Streams.
Try this simple solution:
public String removeDuplicates(String input){
String result = "";
for (int i = 0; i < input.length(); i++) {
if(!result.contains(String.valueOf(input.charAt(i)))) {
result += String.valueOf(input.charAt(i));
}
}
return result;
}
I would use the help of LinkedHashSet. Removes dups (as we are using a Set, maintains the order as we are using linked list impl). This is kind of a dirty solution. there might be even a better way.
String s="aabbccdef";
Set<Character> set=new LinkedHashSet<Character>();
for(char c:s.toCharArray())
{
set.add(Character.valueOf(c));
}
Create a StringWriter. Run through the original string using charAt(i) in a for loop. Maintain a variable of char type keeping the last charAt value. If you iterate and the charAt value equals what is stored in that variable, don't add to the StringWriter. Finally, use the StringWriter.toString() method and get a string, and do what you need with it.
Here is an improvement to the answer by Dave.
It uses HashSet instead of the slightly more costly LinkedHashSet, and reuses the chars buffer for the result, eliminating the need for a StringBuilder.
String string = "aabbccdefatafaz";
char[] chars = string.toCharArray();
Set<Character> present = new HashSet<>();
int len = 0;
for (char c : chars)
if (present.add(c))
chars[len++] = c;
System.out.println(new String(chars, 0, len)); // abcdeftz
Java 8 has a new String.chars() method which returns a stream of characters in the String. You can use stream operations to filter out the duplicate characters like so:
String out = in.chars()
.mapToObj(c -> Character.valueOf((char) c)) // bit messy as chars() returns an IntStream, not a CharStream (which doesn't exist)
.distinct()
.map(Object::toString)
.collect(Collectors.joining(""));
String input = "AAAB";
String output = "";
for (int index = 0; index < input.length(); index++) {
if (input.charAt(index % input.length()) != input
.charAt((index + 1) % input.length())) {
output += input.charAt(index);
}
}
System.out.println(output);
but you cant use it if the input has the same elements, or if its empty!
Code to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine. An extra array is not:
import java.util.*;
public class Main{
public static char[] removeDupes(char[] arr){
if (arr == null || arr.length < 2)
return arr;
int len = arr.length;
int tail = 1;
for(int x = 1; x < len; x++){
int y;
for(y = 0; y < tail; y++){
if (arr[x] == arr[y]) break;
}
if (y == tail){
arr[tail] = arr[x];
tail++;
}
}
return Arrays.copyOfRange(arr, 0, tail);
}
public static char[] bigArr(int len){
char[] arr = new char[len];
Random r = new Random();
String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+[]{}|;:',.<>/?`~";
for(int x = 0; x < len; x++){
arr[x] = alphabet.charAt(r.nextInt(alphabet.length()));
}
return arr;
}
public static void main(String args[]){
String result = new String(removeDupes(new char[]{'a', 'b', 'c', 'd', 'a'}));
assert "abcd".equals(result) : "abcda should return abcd but it returns: " + result;
result = new String(removeDupes(new char[]{'a', 'a', 'a', 'a'}));
assert "a".equals(result) : "aaaa should return a but it returns: " + result;
result = new String(removeDupes(new char[]{'a', 'b', 'c', 'a'}));
assert "abc".equals(result) : "abca should return abc but it returns: " + result;
result = new String(removeDupes(new char[]{'a', 'a', 'b', 'b'}));
assert "ab".equals(result) : "aabb should return ab but it returns: " + result;
result = new String(removeDupes(new char[]{'a'}));
assert "a".equals(result) : "a should return a but it returns: " + result;
result = new String(removeDupes(new char[]{'a', 'b', 'b', 'a'}));
assert "ab".equals(result) : "abba should return ab but it returns: " + result;
char[] arr = bigArr(5000000);
long startTime = System.nanoTime();
System.out.println("2: " + new String(removeDupes(arr)));
long endTime = System.nanoTime();
long duration = (endTime - startTime);
System.out.println("Program took: " + duration + " nanoseconds");
System.out.println("Program took: " + duration/1000000000 + " seconds");
}
}
How to read and talk about the above code:
The method called removeDupes takes an array of primitive char called arr.
arr is returned as an array of primitive characters "by value". The arr passed in is garbage collected at the end of Main's member method removeDupes.
The runtime complexity of this algorithm is O(n) or more specifically O(n+(small constant)) the constant being the unique characters in the entire array of primitive chars.
The copyOfRange does not increase runtime complexity significantly since it only copies a small constant number of items. The char array called arr is not stepped all the way through.
If you pass null into removeDupes, the method returns null.
If you pass an empty array of primitive chars or an array containing one value, that unmodified array is returned.
Method removeDupes goes about as fast as physically possible, fully utilizing the L1 and L2 cache, so Branch redirects are kept to a minimum.
A 2015 standard issue unburdened computer should be able to complete this method with an primitive char array containing 500 million characters between 15 and 25 seconds.
Explain how this code works:
The first part of the array passed in is used as the repository for the unique characters that are ultimately returned. At the beginning of the function the answer is: "the characters between 0 and 1" as between 0 and tail.
We define the variable y outside of the loop because we want to find the first location where the array index that we are looking at has been duplicated in our repository. When a duplicate is found, it breaks out and quits, the y==tail returns false and the repository is not contributed to.
when the index x that we are peeking at is not represented in our repository, then we pull that one and add it to the end of our repository at index tail and increment tail.
At the end, we return the array between the points 0 and tail, which should be smaller or equal to in length to the original array.
Talking points exercise for coder interviews:
Will the program behave differently if you change the y++ to ++y? Why or why not.
Does the array copy at the end represent another 'N' pass through the entire array making runtime complexity O(n*n) instead of O(n) ? Why or why not.
Can you replace the double equals comparing primitive characters with a .equals? Why or why not?
Can this method be changed in order to do the replacements "by reference" instead of as it is now, "by value"? Why or why not?
Can you increase the efficiency of this algorithm by sorting the repository of unique values at the beginning of 'arr'? Under which circumstances would it be more efficient?
public class RemoveRepeated4rmString {
public static void main(String[] args) {
String s = "harikrishna";
String s2 = "";
for (int i = 0; i < s.length(); i++) {
Boolean found = false;
for (int j = 0; j < s2.length(); j++) {
if (s.charAt(i) == s2.charAt(j)) {
found = true;
break; //don't need to iterate further
}
}
if (found == false) {
s2 = s2.concat(String.valueOf(s.charAt(i)));
}
}
System.out.println(s2);
}
}
public static void main(String a[]){
String name="Madan";
System.out.println(name);
StringBuilder sb=new StringBuilder(name);
for(int i=0;i<name.length();i++){
for(int j=i+1;j<name.length();j++){
if(name.charAt(i)==name.charAt(j)){
sb.deleteCharAt(j);
}
}
}
System.out.println("After deletion :"+sb+"");
}
import java.util.Scanner;
public class dublicate {
public static void main(String... a) {
System.out.print("Enter the String");
Scanner Sc = new Scanner(System.in);
String st=Sc.nextLine();
StringBuilder sb=new StringBuilder();
boolean [] bc=new boolean[256];
for(int i=0;i<st.length();i++)
{
int index=st.charAt(i);
if(bc[index]==false)
{
sb.append(st.charAt(i));
bc[index]=true;
}
}
System.out.print(sb.toString());
}
}
To me it looks like everyone is trying way too hard to accomplish this task. All we are concerned about is that it copies 1 copy of each letter if it repeats. Then because we are only concerned if those characters repeat one after the other the nested loops become arbitrary as you can just simply compare position n to position n + 1. Then because this only copies things down when they're different, to solve for the last character you can either append white space to the end of the original string, or just get it to copy the last character of the string to your result.
String removeDuplicate(String s){
String result = "";
for (int i = 0; i < s.length(); i++){
if (i + 1 < s.length() && s.charAt(i) != s.charAt(i+1)){
result = result + s.charAt(i);
}
if (i + 1 == s.length()){
result = result + s.charAt(i);
}
}
return result;
}
String str1[] ="Hi helloo helloo oooo this".split(" ");
Set<String> charSet = new LinkedHashSet<String>();
for (String c: str1)
{
charSet.add(c);
}
StringBuilder sb = new StringBuilder();
for (String character : charSet)
{
sb.append(character);
}
System.out.println(sb.toString());
I think working this way would be more easy,,,
Just pass a string to this function and the job is done :) .
private static void removeduplicate(String name)
{ char[] arr = name.toCharArray();
StringBuffer modified =new StringBuffer();
for(char a:arr)
{
if(!modified.contains(Character.toString(a)))
{
modified=modified.append(Character.toString(a)) ;
}
}
System.out.println(modified);
}
public class RemoveDuplicatesFromStingsMethod1UsingLoops {
public static void main(String[] args) {
String input = new String("aaabbbcccddd");
String output = "";
for (int i = 0; i < input.length(); i++) {
if (!output.contains(String.valueOf(input.charAt(i)))) {
output += String.valueOf(input.charAt(i));
}
}
System.out.println(output);
}
}
output: abcd
You can't. You can create a new String that has duplicates removed. Why aren't you using StringBuilder (or StringBuffer, presumably)?
You can run through the string and store the unique characters in a char[] array, keeping track of how many unique characters you've seen. Then you can create a new String using the String(char[], int, int) constructor.
Also, the problem is a little ambiguous—does “duplicates” mean adjacent repetitions? (In other words, what should happen with abcab?)
Oldschool way (as we wrote such a tasks in Apple ][ Basic, adapted to Java):
int i,j;
StringBuffer str=new StringBuffer();
Scanner in = new Scanner(System.in);
System.out.print("Enter string: ");
str.append(in.nextLine());
for (i=0;i<str.length()-1;i++){
for (j=i+1;j<str.length();j++){
if (str.charAt(i)==str.charAt(j))
str.deleteCharAt(j);
}
}
System.out.println("Removed non-unique symbols: " + str);
Here is another logic I'd like to share. You start comparing from midway of the string length and go backward.
Test with:
input = "azxxzy";
output = "ay";
String removeMidway(String input){
cnt = cnt+1;
StringBuilder str = new StringBuilder(input);
int midlen = str.length()/2;
for(int i=midlen-1;i>0;i--){
for(int j=midlen;j<str.length()-1;j++){
if(str.charAt(i)==str.charAt(j)){
str.delete(i, j+1);
midlen = str.length()/2;
System.out.println("i="+i+",j="+j+ ",len="+ str.length() + ",midlen=" + midlen+ ", after deleted = " + str);
}
}
}
return str.toString();
}
Another possible solution, in case a string is an ASCII string, is to maintain an array of 256 boolean elements to denote ASCII character appearance in a string. If a character appeared for the first time, we keep it and append to the result. Otherwise just skip it.
public String removeDuplicates(String input) {
boolean[] chars = new boolean[256];
StringBuilder resultStringBuilder = new StringBuilder();
for (Character c : input.toCharArray()) {
if (!chars[c]) {
resultStringBuilder.append(c);
chars[c] = true;
}
}
return resultStringBuilder.toString();
}
This approach will also work with Unicode string. You just need to increase chars size.
Solution using JDK7:
public static String removeDuplicateChars(final String str){
if (str == null || str.isEmpty()){
return str;
}
final char[] chArray = str.toCharArray();
final Set<Character> set = new LinkedHashSet<>();
for (char c : chArray) {
set.add(c);
}
final StringBuilder sb = new StringBuilder();
for (Character character : set) {
sb.append(character);
}
return sb.toString();
}
String str = "eamparuthik#gmail.com";
char[] c = str.toCharArray();
String op = "";
for(int i=0; i<=c.length-1; i++){
if(!op.contains(c[i] + ""))
op = op + c[i];
}
System.out.println(op);
public static String removeDuplicateChar(String str){
char charArray[] = str.toCharArray();
StringBuilder stringBuilder= new StringBuilder();
for(int i=0;i<charArray.length;i++){
int index = stringBuilder.toString().indexOf(charArray[i]);
if(index <= -1){
stringBuilder.append(charArray[i]);
}
}
return stringBuilder.toString();
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class RemoveDuplicacy
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter any word : ");
String s = br.readLine();
int l = s.length();
char ch;
String ans=" ";
for(int i=0; i<l; i++)
{
ch = s.charAt(i);
if(ch!=' ')
ans = ans + ch;
s = s.replace(ch,' '); //Replacing all occurrence of the current character by a space
}
System.out.println("Word after removing duplicate characters : " + ans);
}
}
public static void main(String[] args) {
int i,j;
StringBuffer str=new StringBuffer();
Scanner in = new Scanner(System.in);
System.out.print("Enter string: ");
str.append(in.nextLine());
for (i=0;i<str.length()-1;i++)
{
for (j=1;j<str.length();j++)
{
if (str.charAt(i)==str.charAt(j))
str.deleteCharAt(j);
}
}
System.out.println("Removed String: " + str);
}
This is improvement on solution suggested by #Dave. Here, I am implementing in single loop only.
Let's reuse the return of set.add(T item) method and add it simultaneously in StringBuffer if add is successfull
This is just O(n). No need to make a loop again.
String string = "aabbccdefatafaz";
char[] chars = string.toCharArray();
StringBuilder sb = new StringBuilder();
Set<Character> charSet = new LinkedHashSet<Character>();
for (char c : chars) {
if(charSet.add(c) ){
sb.append(c);
}
}
System.out.println(sb.toString()); // abcdeftz
Simple solution is to iterate through the given string and put each unique character into another string(in this case, a variable result ) if this string doesn't contain that particular character.Finally return result string as output.
Below is working and tested code snippet for removing duplicate characters from the given string which has O(n) time complexity .
private static String removeDuplicate(String s) {
String result="";
for (int i=0 ;i<s.length();i++) {
char ch = s.charAt(i);
if (!result.contains(""+ch)) {
result+=""+ch;
}
}
return result;
}
If the input is madam then output will be mad.
If the input is anagram then output will be angrm
Hope this helps.
Thanks
For the simplicity of the code- I have taken hardcore input, one can take input by using Scanner class also
public class KillDuplicateCharInString {
public static void main(String args[]) {
String str= "aaaabccdde ";
char arr[]= str.toCharArray();
int n = arr.length;
String finalStr="";
for(int i=0;i<n;i++) {
if(i==n-1){
finalStr+=arr[i];
break;
}
if(arr[i]==arr[i+1]) {
continue;
}
else {
finalStr+=arr[i];
}
}
System.out.println(finalStr);
}
}
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String s = sc.next();
String str = "";
char c;
for(int i = 0; i < s.length(); i++)
{
c = s.charAt(i);
str = str + c;
s = s.replace(c, ' ');
if(i == s.length() - 1)
{
System.out.println(str.replaceAll("\\s", ""));
}
}
}
package com.st.removeduplicate;
public class RemoveDuplicate {
public static void main(String[] args) {
String str1="shushil",str2="";
for(int i=0; i<=str1.length()-1;i++) {
int count=0;
for(int j=0;j<=i;j++) {
if(str1.charAt(i)==str1.charAt(j))
count++;
if(count >1)
break;
}
if(count==1)
str2=str2+str1.charAt(i);
}
System.out.println(str2);
}
}
Related
This is what I got. It works for now, but if I type, for example, "I like bananas", I get 'pIp ppipkpep pbpapnpapnpaps', while I'm aiming to get 'pI pLpipkpe pbpapnpapnpaps.
Every solution I tried came down to using an 'if statement', trying to check if the character at said position in the original 'encText'is equal to ' ', and if so, making it equal to ' ' as well in the newText array before checking if the position required an 'p' or the char from the original array.. However, everytime I tried that, I'd get an array out of bounds exception.
static void pEncrypt() {
System.out.println("Adding P");
Scanner in = new Scanner(System.in);
String encText = in.nextLine();
int k = encText.length();
char[] charsEncText = encText.toCharArray();
char[] newText = new char[2*k];
int j = 1;
for (int i = 0; i < (k*2); i++) {
if (i%2 == 0) {
newText[i] = 'p';
} else {
newText[i] = charsEncText[i-j];
j++;
}
}
System.out.println(newText);
}
A simpler solution is to use replaceAll with a positive lookahead.
String str = "I like bananas";
String res = str.replaceAll("(?=[^ ])", "p");
System.out.println(res); // "pI plpipkpe pbpapnpapnpaps"
Demo
You can try this way.
static void pEncrypt() {
System.out.println("Adding P");
Scanner in = new Scanner(System.in);
String encText = in.nextLine();
int k = encText.length();
char[] charsEncText = encText.toCharArray();
char[] newText = new char[2*k];
int j=0;
for(int i=0;i<k;i++)
{
if(charsEncText[i]==' ')
{
newText[j]=charsEncText[i];
j++;
}
else{
newText[j]='p';
newText[j+1]=charsEncText[i];
j=j+2;
}
}
System.out.println(newText);
}
Assuming one does not need a char[], I would just concatenate to a String. Something like:
public static String pEncrypt(String org)
{
String ret = "";
for (int i = 0; i < org.length(); ++i) {
char ch = org.charAt(i);
if (ch != ' ') {
ret += "p" + ch;
}
else {
ret += ' ';
}
}
return ret;
}
Also, to make things a bit easier, it is generally a good idea to separate the I/O (i.e., the Scanner and the println) from the processing. That way, one can write test cases rather than attempting to keep inputting the information.
Sample Output:
helloworld ==> phpeplplpopwpoprplpd
I like bananas ==> pI plpipkpe pbpapnpapnpaps
I am trying to print all the unique characters from a string but I am not getting proper output. Also, I want to check if someone enters integer in string, I want to print Invalid String. How can I achieve this?
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char[] ch = new char[20];
System.out.println("Enter the sentence:");
String sent = sc.nextLine().replaceAll(" ", "");
int count = 0;
for (int i = 0; i < sent.length(); i++) {
int j = (sent.length() - 1);
count = 0;
while (j > i) {
if (sent.charAt(j) == sent.charAt(i)) {
sent = deleteCharAt(sent, i);
sent = deleteCharAt(sent, j - 1);
break;
}
j--;
}
}
for (int i = 0; i < sent.length(); i++) {
System.out.println(sent.charAt(i));
}
}
private static String deleteCharAt(String strValue, int index) {
return strValue.substring(0, index) + strValue.substring(index + 1);
}
Enter the sentence:
java is good object oriented programming language
a
v
i
s
o
d
b
c
r
e
e
d
p
g
m
m
n
l
u
You are probably going to want to use a Set. These data structures are like Lists, except:
They do not have an ordering (meaning you cant call set.get(3))
They do not allow duplicates
You can think of them as a Map without any values.
If you have a String and you want to get all the unique chars from it. The steps are as follows:
String string = "hello"; // 4 unique characters
Set<Character> uniqueChars = new HashSet<>(); // create an empty set to put the unique chars into
// split into char[]
char[] chars = string.toCharArray();
Arrays.stream(chars).forEach(c -> {
// the following code will be run once for every char in the array
uniqueChars.add(c);
// adding the same char twice does not insert it twice
});
This can be written more concisely as:
String string = "hello";
Set<Character> uniqueChars = new HashSet<>();
Arrays.stream(string.toCharArray()).forEach(uniqueChars::add); // using a Java 8 method reference
If you want to reject any char that is a numerical digit, you can use the following line:
boolean containsDigit = Arrays.stream(string.toCharArray())
.filter(Character::isDigit) // filter out all the non digit characters
.findAny() // check if there are any remaining
.isPresent();
It would be more efficient and easier to read code to use a HashSet:
HashSet<Character> h = new HashSet<Character>();
for (int i = 0; i <= (sent.length() - 1); i++)
h.add(sent.charAt(i));
Iterator<Character> i = h.iterator();
while (i.hasNext())
System.out.println(i.next());
To avoid duplicate you can use a Set: is a collection that doesn't allow duplicates. You have to use a specific implementation of that interface, such as HashSet. You can do something like this:
public class UniqueChar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence:");
String withoutSpaces = sc.nextLine();
withoutSpaces = "asc34csf"; // mock example
Set<Character> goodChars = new HashSet<>();
String sent = withoutSpaces.replaceAll(" ", "");
int count = 0;
for (int i = 0; i < sent.length(); i++) {
char currChar = sent.charAt(i);
// do not add a character if is a digit
if(Character.isDigit(currChar))
System.out.println("Digit!");
else
goodChars.add(currChar); // add a character only if not present
}
String output = "";
for (Character character : goodChars) {
output += character; // concat in a single output string
}
System.out.println(output);
}
So you simply jump characters that are digits, if it's a character it'll be added to the collection (and the Set manages internally the fact that if it's a duplicate, it will not be added), then concat the elements of the Set in a single String.
You can find more information about HashSet in the Java documentation.
You can write your code something like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] alpha = new int[26];
System.out.println("Enter the sentence:");
String sent = sc.nextLine().replaceAll(" ", "");
for (int i = 0; i < sent.length(); i++) {
int temp = sent[i] - 'a';
if (temp >= 0 && temp <= 25) {
alpha[temp] = 1;
} else {
System.out.println("Invalid String");
return;
}
}
for (int i = 0; i < 26; i++) {
if (alpha[i] == 1)
System.out.println((char) (i + 'a'));
}
}
This uses an array of length 26 as the workaround if you don't want to use any SET like data structure.
This code can bring you problem if your sentence have capital letters as well. You can avoid that problem by using toLowercase like function just before the loop.
I m trying to make a function that prints the number of characters common in given n strings. (note that characters may be used multiple times)
I am struggling to perform this operation on n strings However I did it for 2 strings without any characters repeated more than once.
I have posted my code.
public class CommonChars {
public static void main(String[] args) {
String str1 = "abcd";
String str2 = "bcde";
StringBuffer sb = new StringBuffer();
// get unique chars from both the strings
str1 = uniqueChar(str1);
str2 = uniqueChar(str2);
int count = 0;
int str1Len = str1.length();
int str2Len = str2.length();
for (int i = 0; i < str1Len; i++) {
for (int j = 0; j < str2Len; j++) {
// found match stop the loop
if (str1.charAt(i) == str2.charAt(j)) {
count++;
sb.append(str1.charAt(i));
break;
}
}
}
System.out.println("Common Chars Count : " + count + "\nCommon Chars :" +
sb.toString());
}
public static String uniqueChar(String inputString) {
String outputstr="",temp="";
for(int i=0;i<inputstr.length();i++) {
if(temp.indexOf(inputstr.charAt(i))<0) {
temp+=inputstr.charAt(i);
}
}
System.out.println("completed");
return temp;
}
}
3
abcaa
bcbd
bgc
3
their may be chances that a same character can be present multiple times in
a string and you are not supposed to eliminate those characters instead
check the no. of times they are repeated in other strings. for eg
3
abacd
aaxyz
aatre
output should be 2
it will be better if i get solution in java
You have to convert all Strings to Set of Characters and retain all from the first one. Below solution has many places which could be optimised but you should understand general idea.
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Main {
public static void main(String[] args) {
List<String> input = Arrays.asList("jonas", "ton", "bonny");
System.out.println(findCommonCharsFor(input));
}
public static Collection<Character> findCommonCharsFor(List<String> strings) {
if (strings == null || strings.isEmpty()) {
return Collections.emptyList();
}
Set<Character> commonChars = convertStringToSetOfChars(strings.get(0));
strings.stream().skip(1).forEach(s -> commonChars.retainAll(convertStringToSetOfChars(s)));
return commonChars;
}
private static Set<Character> convertStringToSetOfChars(String string) {
if (string == null || string.isEmpty()) {
return Collections.emptySet();
}
Set<Character> set = new HashSet<>(string.length() + 10);
for (char c : string.toCharArray()) {
set.add(c);
}
return set;
}
}
Above code prints:
[n, o]
A better strategy for your problem is to use this method:
public int[] countChars(String s){
int[] count = new int[26];
for(char c: s.toCharArray()){
count[c-'a']++;
}
return count;
}
Now if you have n Strings (String[] strings) just find the min of common chars for each letter:
int[][] result = new int[n][26]
for(int i = 0; i<strings.length;i++){
result[i] = countChars(s);
}
// now if you sum the min common chars for each counter you are ready
int commonChars = 0;
for(int i = 0; i< 26;i++){
int min = result[0][i];
for(int i = 1; i< n;i++){
if(min>result[j][i]){
min = result[j][i];
}
}
commonChars+=min;
}
Get list of characters for each string:
List<Character> chars1 = s1.chars() // list of chars for first string
.mapToObj(c -> (char) c)
.collect(Collectors.toList());
List<Character> chars2 = s2.chars() // list of chars for second string
.mapToObj(c -> (char) c)
.collect(Collectors.toList());
Then use retainAll method:
chars1.retainAll(chars2); // retain in chars1 only the chars that are contained in the chars2 also
System.out.println(chars1.size());
If you want to get number of unique chars just use Collectors.toSet() instead of toList()
Well if one goes for hashing:
public static int uniqueChars(String first, String second) {
boolean[] hash = new boolean[26];
int count = 0;
//reduce first string to unique letters
for (char c : first.toLowerCase().toCharArray()) {
hash[c - 'a'] = true;
}
//reduce to unique letters in both strings
for(char c : second.toLowerCase().toCharArray()){
if(hash[c - 'a']){
count++;
hash[c - 'a'] = false;
}
}
return count;
}
This is using bucketsort which gives a n+m complexity but needs the 26 buckets(the "hash" array).
Imo one can't do better in regards of complexity as you need to look at every letter at least once which sums up to n+m.
Insitu the best you can get is imho somewhere in the range of O(n log(n) ) .
Your aproach is somewhere in the league of O(n²)
Addon: if you need the characters as a String(in essence the same as above with count is the length of the String returned):
public static String uniqueChars(String first, String second) {
boolean[] hash = new boolean[26];
StringBuilder sb = new StringBuilder();
for (char c : first.toLowerCase().toCharArray()) {
hash[c - 'a'] = true;
}
for(char c : second.toLowerCase().toCharArray()){
if(hash[c - 'a']){
sb.append(c);
hash[c - 'a'] = false;
}
}
return sb.toString();
}
public static String getCommonCharacters(String... words) {
if (words == null || words.length == 0)
return "";
Set<Character> unique = words[0].chars().mapToObj(ch -> (char)ch).collect(Collectors.toCollection(TreeSet::new));
for (String word : words)
unique.retainAll(word.chars().mapToObj(ch -> (char)ch).collect(Collectors.toSet()));
return unique.stream().map(String::valueOf).collect(Collectors.joining());
}
Another variant without creating temporary Set and using Character.
public static String getCommonCharacters(String... words) {
if (words == null || words.length == 0)
return "";
int[] arr = new int[26];
boolean[] tmp = new boolean[26];
for (String word : words) {
Arrays.fill(tmp, false);
for (int i = 0; i < word.length(); i++) {
int pos = Character.toLowerCase(word.charAt(i)) - 'a';
if (tmp[pos])
continue;
tmp[pos] = true;
arr[pos]++;
}
}
StringBuilder buf = new StringBuilder(26);
for (int i = 0; i < arr.length; i++)
if (arr[i] == words.length)
buf.append((char)('a' + i));
return buf.toString();
}
Demo
System.out.println(getCommonCharacters("abcd", "bcde")); // bcd
Alternately display any text that is typed in the textbox
// in either Capital or lowercase depending on the original
// letter changed. For example: CoMpUtEr will convert to
// cOmPuTeR and vice versa.
Switch.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e )
String characters = (SecondTextField.getText()); //String to read the user input
int length = characters.length(); //change the string characters to length
for(int i = 0; i < length; i++) //to check the characters of string..
{
char character = characters.charAt(i);
if(Character.isUpperCase(character))
{
SecondTextField.setText("" + characters.toLowerCase());
}
else if(Character.isLowerCase(character))
{
SecondTextField.setText("" + characters.toUpperCase()); //problem is here, how can i track the character which i already change above, means lowerCase**
}
}}
});
setText is changing the text content to exactly what you give it, not appending it.
Convert the String from the field first, then apply it directly...
String value = "This Is A Test";
StringBuilder sb = new StringBuilder(value);
for (int index = 0; index < sb.length(); index++) {
char c = sb.charAt(index);
if (Character.isLowerCase(c)) {
sb.setCharAt(index, Character.toUpperCase(c));
} else {
sb.setCharAt(index, Character.toLowerCase(c));
}
}
SecondTextField.setText(sb.toString());
You don't have to track whether you've already changed the character from upper to lower. Your code is already doing that since it's basically:
1 for each character x:
2 if x is uppercase:
3 convert x to lowercase
4 else:
5 if x is lowercase:
6 convert x to uppercase.
The fact that you have that else in there (on line 4) means that a character that was initially uppercase will never be checked in the second if statement (on line 5).
Example, start with A. Because that's uppercase, it will be converted to lowercase on line
3 and then you'll go back up to line 1 for the next character.
If you start with z, the if on line 2 will send you directly to line 5 where it will be converted to uppercase. Anything that's neither upper nor lowercase will fail both if statements and therefore remain untouched.
You can use StringUtils.swapCase() from org.apache.commons
This is a better method :-
void main()throws IOException
{
System.out.println("Enter sentence");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
String sentence = "";
for(int i=0;i<str.length();i++)
{
if(Character.isUpperCase(str.charAt(i))==true)
{
char ch2= (char)(str.charAt(i)+32);
sentence = sentence + ch2;
}
else if(Character.isLowerCase(str.charAt(i))==true)
{
char ch2= (char)(str.charAt(i)-32);
sentence = sentence + ch2;
}
else
sentence= sentence + str.charAt(i);
}
System.out.println(sentence);
}
The problem is that you are trying to set the value of SecondTextField after checking every single character in the original string. You should do the conversion "on the side", one character at a time, and only then set the result into the SecondTextField.
As you go through the original string, start composing the output from an empty string. Keep appending the character in the opposite case until you run out of characters. Once the output is ready, set it into SecondTextField.
You can make an output a String, set it to an empty string "", and append characters to it as you go. This will work, but that is an inefficient approach. A better approach would be using a StringBuilder class, which lets you change the string without throwing away the whole thing.
String name = "Vikash";
String upperCase = name.toUpperCase();
String lowerCase = name.toLowerCase();
This is a better approach without using any String function.
public static String ReverseCases(String str) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char temp;
if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
temp = (char)(str.charAt(i) - 32);
}
else if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z'){
temp = (char)(str.charAt(i) + 32);
}
else {
temp = str.charAt(i);
}
sb.append(temp);
}
return sb.toString();
}
Here you are some other version:
public class Palindrom {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a word to check: ");
String checkWord = sc.nextLine();
System.out.println(isPalindrome(checkWord));
sc.close();
}
public static boolean isPalindrome(String str) {
StringBuilder secondSB = new StringBuilder();
StringBuilder sb = new StringBuilder();
sb.append(str);
for(int i = 0; i<sb.length();i++){
char c = sb.charAt(i);
if(Character.isUpperCase(c)){
sb.setCharAt(i, Character.toLowerCase(c));
}
}
secondSB.append(sb);
return sb.toString().equals(secondSB.reverse().toString());
}
}
StringBuilder b = new StringBuilder();
Scanner s = new Scanner(System.in);
String n = s.nextLine();
for(int i = 0; i < n.length(); i++) {
char c = n.charAt(i);
if(Character.isLowerCase(c) == true) {
b.append(String.valueOf(c).toUpperCase());
}
else {
b.append(String.valueOf(c).toLowerCase());
}
}
System.out.println(b);
Methods description:
*toLowerCase()* Returns a new string with all characters converted to lowercase.
*toUpperCase()* Returns a new string with all characters converted to uppercase.
For example:
"Welcome".toLowerCase() returns a new string, welcome
"Welcome".toUpperCase() returns a new string, WELCOME
If you look at characters a-z, you'll see that all of them have the 6th bit is set to 1. Where in A-Z 6th bit is not set.
A = 1000001 a = 1100001
B = 1000010 b = 1100010
C = 1000011 c = 1100011
D = 1000100 d = 1100100
...
Z = 1011010 z = 1111010
So all we need to do is to iterate through each character from a given string and then do XOR(^) with 32. In this way, the 6th bit can swap.
Look at the below code for simply changing the string case without using any if-else conditions.
public final class ChangeStringCase {
public static void main(String[] args) {
String str = "Hello World";
for (int i = 0; i < str.length(); i++) {
char ans = (char)(str.charAt(i) ^ 32);
System.out.print(ans); // Final Output: hELLO wORLD
}
}
}
Time Complexity: O(N) where N = Length of the string.
Space Complexity: O(1)
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String satr=scanner.nextLine();
String newString = "";
for (int i = 0; i < satr.length(); i++) {
if (Character.isUpperCase(satr.charAt(i))) {
newString+=Character.toLowerCase(satr.charAt(i));
}else newString += Character.toUpperCase(satr.charAt(i));
}
System.out.println(newString);
}
public class Toggle {
public static String toggle(String s) {
char[] ch = s.toCharArray();
for (int i = 0; i < s.length(); i++) {
char charat = ch[i];
if (Character.isUpperCase(charat)) {
charat = Character.toLowerCase(charat);
} else
charat = Character.toUpperCase(charat);
System.out.print(charat);
}
return s;
}
public static void main(String[] args) {
toggle("DivYa");
}
}
import java.util.Scanner;
class TestClass {
public static void main(String args[]) throws Exception {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char[] ch = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (Character.isUpperCase(ch[i])) {
ch[i] = Character.toLowerCase(ch[i]);
} else {
ch[i] = Character.toUpperCase(ch[i]);
}
}
System.out.println(ch);
}
}
//This is to convert a letter from upper case to lower case
import java.util.Scanner;
public class ChangeCase {
public static void main(String[]args) {
String input;
Scanner sc= new Scanner(System.in);
System.out.println("Enter Letter from upper case");
input=sc.next();
String result;
result= input.toLowerCase();
System.out.println(result);
}
}
String str1,str2;
Scanner S=new Scanner(System.in);
str1=S.nextLine();
System.out.println(str1);
str2=S.nextLine();
str1=str1.concat(str2);
System.out.println(str1.toLowerCase());
My teacher specifically requested that we split a sentence into words without using String.split(). I've done it using a Vector (which we haven't learned), a while-loop, and substrings. What are other ways of accomplishing this? (preferably without using Vectors/ArrayLists).
I believe that your teacher is asking you to process the string yourself (without using any other libraries to do it for you). Check to see if this is the case - if you can use them, there are things such as StringTokenizer, Pattern, and Scanner to facilitate string processing.
Otherwise...
You will need a list of word separators (such as space, tab, period, etc...) and then walk the array, building a string a character at a time until you hit the word separator. After finding a complete word (you have encountered a word separator character), save it the variable out into your structure (or whatever is required), reset the variable you are building the word in and continue.
Parsing the string character by character, copying each character into a new String, and stopping when you reach a white space character. Then start a new string and continue until you reach the end of the original string.
You can use java.util.StringTokenizer to split a text using desired delimiter. Default delimiter is SPACE/TAB/NEW_LINE.
String myTextToBeSplit = "This is the text to be split into words.";
StringTokenizer tokenizer = new StringTokenizer( myTextToBeSplit );
while ( tokinizer.hasMoreTokens()) {
String word = tokinizer.nextToken();
System.out.println( word ); // word you are looking in
}
As an alternate you can also use java.util.Scanner
Scanner s = new Scanner(myTextToBeSplit).useDelimiter("\\s");
while( s.hasNext() ) {
System.out.println(s.next());
}
s.close();
You can use java.util.Scanner.
import java.util.Arrays;
public class ReverseTheWords {
public static void main(String[] args) {
String s = "hello java how do you do";
System.out.println(Arrays.toString(ReverseTheWords.split(s)));
}
public static String[] split(String s) {
int count = 0;
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == ' ') {
count++;
}
}
String temp = "";
int k = 0;
String[] rev = new String[count + 1];
for (int i = 0; i < c.length; i++) {
if (c[i] == ' ') {
rev[k++] = temp;
temp = "";
} else
temp = temp + c[i];
}
rev[k] = temp;
return rev;
}
}
YOu can use StringTokenizer
http://www.java-samples.com/showtutorial.php?tutorialid=236
Or use a Pattern (also known as a regular expression) to try to match the words.
Use a Scanner with ctor (String)
regular expressions and match
StringTokenizer
iterating yourself char by char
recursive iteration
Without using a Vector/List (and without manually re-implementing their ability to re-size themselves for your function), you can take advantage of the simple observation that a string of length N cannot have more than (N+1)/2 words (in integer division). You can declare an array of strings of that size, populate it the same way you populated that Vector, and then copy the results to an array of the size of the number of words you found.
So:
String[] mySplit( String in ){
String[] bigArray = new String[ (in.length()+1)/2 ];
int numWords = 0;
// Populate bigArray with your while loop and keep
// track of the number of words
String[] result = new String[numWords];
// Copy results from bigArray to result
return result;
}
public class MySplit {
public static String[] mySplit(String text,String delemeter){
java.util.List<String> parts = new java.util.ArrayList<String>();
text+=delemeter;
for (int i = text.indexOf(delemeter), j=0; i != -1;) {
parts.add(text.substring(j,i));
j=i+delemeter.length();
i = text.indexOf(delemeter,j);
}
return parts.toArray(new String[0]);
}
public static void main(String[] args) {
String str="012ab567ab0123ab";
String delemeter="ab";
String result[]=mySplit(str,delemeter);
for(String s:result)
System.out.println(s);
}
}
public class sha1 {
public static void main(String[] args) {
String s = "hello java how do you do";
System.out.println(Arrays.toString(sha1.split(s)));
}
public static String[] split(String s) {
int count = 0;
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == ' ') {
count++;
}
}
String temp = "";
int k = 0;
String[] rev = new String[count + 1];
for (int i = c.length-1; i >= 0; i--) {
if (c[i] == ' ') {
rev[k++] = temp;
temp = "";
} else
temp = temp + c[i];
}
rev[k] = temp;
return rev;
}
}
Simple touch.! Improve if you want to.
package com.asif.test;
public class SplitWithoutSplitMethod {
public static void main(String[] args) {
split('#',"asif#is#handsome");
}
static void split(char delimeter, String line){
String word = "";
String wordsArr[] = new String[3];
int k = 0;
for(int i = 0; i <line.length(); i++){
if(line.charAt(i) != delimeter){
word+= line.charAt(i);
}else{
wordsArr[k] = word;
word = "";
k++;
}
}
wordsArr[k] = word;
for(int j = 0; j <wordsArr.length; j++)
System.out.println(wordsArr[j]);
}
}
Please try this .
public static String[] mysplit(String mystring) {
String string=mystring+" "; //append " " bcz java string does not hava any ending character
int[] spacetracker=new int[string.length()];// to count no. of spaces in string
char[] array=new char[string.length()]; //store all non space character
String[] tokenArray=new String[string.length()];//to return token of words
int spaceIndex=0;
int parseIndex=0;
int arrayIndex=0;
int k=0;
while(parseIndex<string.length())
{
if(string.charAt(parseIndex)==' '||string.charAt(parseIndex)==' ')
{
spacetracker[spaceIndex]=parseIndex;
spaceIndex++;
parseIndex++;
}else
{
array[arrayIndex]=string.charAt(parseIndex);
arrayIndex++;
parseIndex++;
}
}
for(int i=0;i<spacetracker.length;i++)
{
String token="";
for(int j=k;j<(spacetracker[i])-i;j++)
{
token=token+array[j];
k++;
}
tokenArray[i]=token;
//System.out.println(token);
token="";
}
return tokenArray;
}
Hope this helps
import java.util.*;
class StringSplit {
public static void main(String[] args)
{
String s="splitting a string without using split()";
ArrayList<Integer> al=new ArrayList<Integer>(); //Instead you can also use a String
ArrayList<String> splitResult=new ArrayList<String>();
for(int i=0;i<s.length();i++)
if(s.charAt(i)==' ')
al.add(i);
al.add(0, 0);
al.add(al.size(),s.length());
String[] words=new String[al.size()];
for(int j=0;j<=words.length-2;j++)
splitResult.add(s.substring(al.get(j),al.get(j+1)).trim());
System.out.println(splitResult);
}
}
Time complexity: O(n)
You can use java Pattern to do it in easy way.
package com.company;
import java.util.regex.Pattern;
public class umeshtest {
public static void main(String a[]) {
String ss = "I'm Testing and testing the new feature";
Pattern.compile(" ").splitAsStream(ss).forEach(s -> System.out.println(s));
}
}
You can also use String.substring or charAt[].