how to print only certain letters - java

so I have this task where I must enter two strings and after that I have to find what are there common letters,and then write them out but only once..so for example
if the string1 is "onomatopoeia" and string2 is "conversation" I should get back:
o,n,a,t,e,i... My only problem is the last part("I don't know how to write the letters only once)
here is my code
import java.util.Scanner;
import java.util.Arrays;
public class Zadatak4 {
/**
* #param args
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
char niz[] = new char[100];
char niz2[] = new char[100];
System.out.print("Add the first string: ");
niz = scan.nextLine().toCharArray();
System.out.print("Add the second string: ");
niz2 = scan.nextLine().toCharArray();
for (int i = 0; i < niz.length; i++) {
for (int j = 0; j < niz2.length; j++) {
if (niz[i] == niz2[j]) {
System.out.println(niz[i] + " ");
// What now!?!?!?
}
}
}
}
}

Use a set:
LinkedHashSet<string> printNum = new LinkedHashSet<string>();
if(niz[i] == niz2[j])
{
printNum.add( niz[i] );
}
// outside of loop
for( string s : printNum )
{
System.out.println(s);
}

in the innermost section of your for loop you're going to want to add them to a set
mutuals.add(niz[i])
then outside the loop at the beginning add this to declare it
Set<char> mutuals = new HashSet<char>()
make sure you do this OUTSIDE the loop
then afterwards, print out everything in mutuals

You could do this by utilizing two HashSets.
You have one hashset per word. When you encounter a letter in word1 you enter in set1.
When you encounter letter in word2 you enter in set2.
Finally, you only keep the letters that are in both sets.
import java.util.HashSet;
public class Zadatak4 {
/**
* #param args
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
char niz[] = new char[100];
char niz2[] = new char[100];
System.out.print("Add the first string: ");
niz = scan.nextLine().toCharArray();
System.out.print("Add the second string: ");
niz2 = scan.nextLine().toCharArray();
HashSet<Integer> set1 = new <String>HashSet();
HashSet<Integer> set2 = new <String>HashSet();
for(int i = 0; i < niz.length; i++)
{
if(!set1.contains(niz[i]));
set1.add((int) niz[i]);
}
for(int i = 0; i < niz2.length; i++)
{
if(!set2.contains(niz2[i]));
set2.add((int) niz2[i]);
}
Iterator<Integer> it = set1.iterator();
int currentChar;
while(it.hasNext())
{
currentChar = it.next();
if(set2.contains(currentChar))
System.out.println((char)currentChar);
}
}
}

What you need is an intersection of the two sets, so what you could use is Set.retainAll().

Almost everyone suggesting Set, here is the hard way of doing it...
public static void main(String[] args) {
String printed = "";
Scanner scan = new Scanner(System.in);
char niz[] = new char[100];
char niz2[] = new char[100];
System.out.print("Add the first string: ");
niz = scan.nextLine().toCharArray();
System.out.print("Add the second string: ");
niz2 = scan.nextLine().toCharArray();
for(int i = 0; i < niz.length; i++)
{
for(int j = 0; j < niz2.length; j++)
{
if(niz[i] == niz2[j])
{
if(printed.indexOf(niz[i]) == -1) {
System.out.println(niz[i]+" ");
}
printed += niz[i];
}
}
}

A one liner :
HashSet<Character> common =
new HashSet<Character>(Arrays.asList(niz1)).retainAll(
new HashSet<Character>(Arrays.asList(niz2)));

Store the char in Set in
Set<Character> cs=new HashSet<>();
if(niz[i] == niz2[j])
{
cs.add(niz[i]);
//System.out.println(niz[i]+" ");
//What now!?!?!?
}

Related

How to make sure the Print statement is executed only when the characters are distinct?

So, I'm writing a program for String compression. if the input is aabbccc, the output should be a2b2c3.
But in my program, my output is a2a2b2b2c3c3c3. That is because my Print statement is in a for loop. Which isn't supposed to be there.
How can I execute the print statement only when two characters in the String are not equal? so that I get the right output?
I've tried other ways of doing the String Compression program, but this way using Collections seems the easiest to me.
public class Compress {
static int i;
static int freq;
public static void main(String args[]) {
System.out.println("Enter a String");
Scanner sc= new Scanner(System.in);
String str=sc.nextLine();
List<Character> arrlist = new ArrayList<Character>();
for(int i=0; i<str.length();i++){
arrlist.add(str.charAt(i));
}
for(int i=0; i<str.length();i++){
freq = Collections.frequency(arrlist, str.charAt(i));
System.out.print(str.charAt(i)+""+freq);
}
}
}
Desired result
Input: aabbccc
Output: a2b2c3
What I'm getting
Input: aabbccc
Output: a2a2b2b2c3c3c3
You can use the following code, there is no need to have 2 nested loops to do the compression. One loop passing through the input string is more than enough.
class Compress {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
scanner.close();
System.out.println("Compressed Input: " + compressInput(inputString));
}
private static String compressInput(String str) {
if(str.isEmpty())
return "";
if(str.length() == 1)
return str + "1";
StringBuilder result = new StringBuilder();
int cmpt = 1;
for (int i = 1; i < str.length(); i++) {
if(str.charAt(i - 1) == str.charAt(i))
cmpt++;
else {
result.append(str.charAt(i-1));
result.append(cmpt);
cmpt=1;
}
}
result.append(str.charAt(str.length()-1));
result.append(cmpt);
return result.toString();
}
}
Example of output:
Enter a string: aaabbbbccddddeeeefg
Compressed Input: a3b4c2d4e4f1g1
Collections.frequency does give you the count as you can see in your output, but the problem here is that you need to group by each character in the String.
Make use of a Map:
Map<Character, Long> countMap = new HashMap<>();
for (int i = 0; i < inputString.length(); i++) {
countMap.merge(Character.valueOf(inputString.charAt(i)), 1L, (k, v) -> k + v);
}
countMap.forEach((k, v) -> System.out.print(k + "" + v));
You could also do it in a similar manner as below. I have made use of a map wherein the key is the character and the value is the frequency of occurrence.
public class Compress {
static int i;
static int freq;
public static void main(String args[]) {
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
HashMap<Character, Integer> hmap = new HashMap<>();
String str = sc.nextLine();
List<Character> arrlist = new ArrayList<Character>();
for (int i = 0; i < str.length(); i++) {
arrlist.add(str.charAt(i));
}
for (int i = 0; i < str.length(); i++) {
freq = Collections.frequency(arrlist, str.charAt(i));
hmap.put(str.charAt(i), freq);
}
for (Character c : hmap.keySet()) {
System.out.print(c + "" + hmap.get(c));
}
}
}

How to remove duplicate words in string and display them in same order

This is my program to remove duplicate words in a string using set the program
works fine removing duplicate elements, but the output is not in the correct order
public class Remove_DuplicateIN_String {
public static void main(String a[]) throws IOException {
String a1;//=new String[200];
int i;
InputStreamReader reader=new InputStreamReader(System.in);
BufferedReader in =new BufferedReader(reader);
System.out.println("Enter the String ");
a1=(in.readLine());
System.out.print(a1);
System.out.println("\n");
String words[]=new String[100];
words=a1.split(" ");
System.out.println(words.length);
Set<String> uniq=new HashSet<String>();
for(i=0;i<words.length;i++)
{
uniq.add(words[i]);
}
Iterator it=uniq.iterator();
while(it.hasNext())
{
System.out.print(it.next()+" ");
}
}
}
Enter the String
hi hi world hello a
hi hi world hello a
5
hi a world hello
I want output as hi world hello a
Use LinkedHashSet
It maintains order and avoid duplicates.
Set wordSet = new LinkedHashSet();
Use LinkedHashSet.
It will track order and also avoid duplicates of elements.
Set<String> linkedHashSet = new LinkedHashSet<String>();
If you have already stored elements in array of strings, you can use collection api to addAll into set.
String words[]=a1.split(" ");
Set<String> linkedHashSet=new LinkedHashSet<String>();
linkedHashSet.addAll(Arrays.asList(words));.
package StringPrograms;
import java.util.Scanner;
public class RemoveDuplicateWords {
public static void main(String[] args) {
boolean flag;
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String[] str = input.split(" ");
int count = 0;
String[] out = new String[str.length];
for (int i = 0; i < str.length; i++) {
flag = true;
for (int j = 0; j <count; j++) {
if (str[i].equalsIgnoreCase(out[j])) {
flag = false;
break;
}
}
if (flag) {
out[count] = str[i];
count++;
}
}
for (int k = 0; k < out.length; k++) {
if (out[k] != null)
System.out.print(out[k] + " ");
}
}
}
String noDuplicates = Arrays.asList(startingString.split(" ")).stream()
.distinct()
.collect(Collectors.join(" "));
This approach doesn't handle commas and special characters though.

Java words reverse

I am new to Java and I found a interesting problem which I wanted to solve. I am trying to code a program that reverses the position of each word of a string. For example, the input string = "HERE AM I", the output string will be "I AM HERE". I have got into it, but it's not working out for me. Could anyone kindly point out the error, and how to fix it, because I am really curious to know what's going wrong. Thanks!
import java.util.Scanner;
public class Count{
static Scanner sc = new Scanner(System.in);
static String in = ""; static String ar[];
void accept(){
System.out.println("Enter the string: ");
in = sc.nextLine();
}
void intArray(int words){
ar = new String[words];
}
static int Words(String in){
in = in.trim(); //Rm space
int wc = 1;
char c;
for (int i = 0; i<in.length()-1;i++){
if (in.charAt(i)==' '&&in.charAt(i+1)!=' ') wc++;
}
return wc;
}
void generate(){
char c; String w = ""; int n = 0;
for (int i = 0; i<in.length(); i++){
c = in.charAt(i);
if (c!=' '){
w += c;
}
else {
ar[n] = w; n++;
}
}
}
void printOut(){
String finale = "";
for (int i = ar.length-1; i>=0;i--){
finale = finale + (ar[i]);
}
System.out.println("Reversed words: " + finale);
}
public static void main(String[] args){
Count a = new Count();
a.accept();
int words = Words(in);
a.intArray(words);
a.generate();
a.printOut();
}
}
Got it. Here is my code that implements split and reverse from scratch.
The split function is implemented through iterating through the string, and keeping track of start and end indexes. Once one of the indexes in the string is equivalent to a " ", the program sets the end index to the element behind the space, and adds the previous substring to an ArrayList, then creating a new start index to begin with.
Reverse is very straightforward - you simply iterate from the end of the string to the first element of the string.
Example:
Input: df gf sd
Output: sd gf df
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Count{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter string to reverse: ");
String unreversed = scan.nextLine();
System.out.println("Reversed String: " + reverse(unreversed));
}
public static String reverse(String unreversed)
{
ArrayList<String> parts = new ArrayList<String>();
String reversed = "";
int start = 0;
int end = 0;
for (int i = 0; i < unreversed.length(); i++)
{
if (unreversed.charAt(i) == ' ')
{
end = i;
parts.add(unreversed.substring(start, end));
start = i + 1;
}
}
parts.add(unreversed.substring(start, unreversed.length()));
for (int i = parts.size()-1; i >= 0; i--)
{
reversed += parts.get(i);
reversed += " ";
}
return reversed;
}
}
There is my suggestion :
String s = " HERE AM I ";
s = s.trim();
int j = s.length() - 1;
int index = 0;
StringBuilder builder = new StringBuilder();
for (int i = j; i >= 0; i--) {
Character c = s.charAt(i);
if (c.isWhitespace(c)) {
index = i;
String r = s.substring(index+1, j+1);
j = index - 1;
builder.append(r);
builder.append(" ");
}
}
String r=s.substring(0, index);
builder.append(r);
System.out.println(builder.toString());
From adding debug output between each method call it's easy to determine that you're successfully reading the input, counting the words, and initializing the array. That means that the problem is in generate().
Problem 1 in generate() (why "HERE" is duplicated in the output): after you add w to your array (when the word is complete) you don't reset w to "", meaning every word has the previous word(s) prepended to it. This is easily seen by adding debug output (or using a debugger) to print the state of ar and w each iteration of the loop.
Problem 2 in generate() (why "I" isn't in the output): there isn't a trailing space in the string, so the condition that adds a word to the array is never met for the last word before the loop terminates at the end of the string. The easy fix is to just add ar[n] = w; after the end of the loop to cover the last word.
I would use the split function and then print from the end of the list to the front.
String[] splitString = str.split(" ");
for(int i = splitString.length() - 1; i >= 0; i--){
System.out.print(splitString[i]);
if(i != 0) System.out.print(' ');
}
Oops read your comment. Disregard this if it is not what you want.
This has a function that does the same as split, but not the predefined split function
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string : ");
String input = sc.nextLine();
// This splits the string into array of words separated with " "
String arr[] = myOwnSplit(input.trim(), ' '); // ["I", "AM", "HERE"]
// This ll contain the reverse string
String rev = "";
// Reading the array from the back
for(int i = (arr.length - 1) ; i >= 0 ; i --) {
// putting the words into the reverse string with a space to it's end
rev += (arr[i] + " ");
}
// Getting rid of the last extra space
rev.trim();
System.out.println("The reverse of the given string is : " + rev);
}
// The is my own version of the split function
public static String[] myOwnSplit(String str, char regex) {
char[] arr = str.toCharArray();
ArrayList<String> spltedArrayList = new ArrayList<String>();
String word = "";
// splitting the string based on the regex and bulding an arraylist
for(int i = 0 ; i < arr.length ; i ++) {
char c = arr[i];
if(c == regex) {
spltedArrayList.add(word);
word = "";
} else {
word += c;
}
if(i == (arr.length - 1)) {
spltedArrayList.add(word);
}
}
String[] splitedArray = new String[spltedArrayList.size()];
// Converting the arraylist to string array
for(int i = 0 ; i < spltedArrayList.size() ; i++) {
splitedArray[i] = spltedArrayList.get(i);
}
return splitedArray;
}

How to remove duplicate character from a string in java?

In my program, the user enters a string, and it first finds the largest mode of characters in the string. Next, my program is supposed to remove all duplicates of a character in a string, (user input: aabc, program prints: abc) which I'm not entirely certain on how to do. I can get it to remove duplicates from some strings, but not all. For example, when the user puts "aabc" it will print "abc", but if the user puts "aabbhh", it will print "abbhh." Also, before I added the removeDup method to my program, it would only print the maxMode once, but after I added the removeDup method, it began to print the maxMode twice. How do I keep it from printing it twice?
Note: I cannot convert the strings to an array.
import java.util.Scanner;
public class JavaApplication3 {
static class MyStrings {
String s;
void setMyStrings(String str) {
s = str;
}
int getMode() {
int i;
int j;
int count = 0;
int maxMode = 0, maxCount = 1;
for (i = 0; i< s.length(); i++) {
maxCount = count;
count = 0;
for (j = s.length()-1; j >= 0; j--) {
if (s.charAt(j) == s.charAt(i))
count++;
if (count > maxCount){
maxCount = count;
maxMode = i;
}
}
}
System.out.println(s.charAt(maxMode)+" = largest mode");
return maxMode;
}
String removeDup() {
getMode();
int i;
int j;
String rdup = "";
for (i = 0; i< s.length(); i++) {
int count = 1;
for (j = 0; j < rdup.length(); j++) {
if (s.charAt(i) == s.charAt(j)){
count++;
}
}
if (count == 1){
rdup += s.charAt(i);
}
}
System.out.print(rdup);
System.out.println();
return rdup;
}
}
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
MyStrings setS = new MyStrings();
String s;
System.out.print("Enter string:");
s = in.nextLine();
setS.setMyStrings(s);
setS.getMode();
setS.removeDup();
}
}
Try this method...should work fine!
String removeDup()
{
getMode();
int i;
int j;
String rdup = "";
for (i = 0; i< s.length(); i++) {
int count = 1;
for (j = i+1; j < s.length(); j++) {
if (s.charAt(i) == s.charAt(j)) {
count++;
}
}
if (count == 1){
rdup += s.charAt(i);
}
}
// System.out.print(rdup);
System.out.println();
return rdup;
}
Welcome to StackOverflow!
You're calling getMode() both outside and inside of removeDup(), which is why it's printing it twice.
In order to remove all duplicates, you'll have to call removeDup() over and over until all the duplicates are gone from your string. Right now you're only calling it once.
How might you do that? Think about how you're detecting duplicates, and use that as the end condition for a while loop or similar.
Happy coding!
Shouldn't this be an easier way? Also, i'm still learning.
import java.util.*;
public class First {
public static void main(String arg[])
{
Scanner sc= new Scanner(System.in);
StringBuilder s=new StringBuilder(sc.nextLine());
//String s=new String();
for(int i=0;i<s.length();i++){
String a=s.substring(i, i+1);
while(s.indexOf(a)!=s.lastIndexOf(a)){s.deleteCharAt(s.lastIndexOf(a));}
}
System.out.println(s.toString());
}
}
You can do this:
public static void main(String[] args) {
String str = new String("PINEAPPLE");
Set <Character> letters = new <Character>HashSet();
for (int i = 0; i < str.length(); i++) {
letters.add(str.charAt(i));
}
System.out.println(letters);
}
I think an optimized version which supports ASCII codes can be like this:
public static void main(String[] args) {
System.out.println(removeDups("*PqQpa abbBBaaAAzzK zUyz112235KKIIppP!!QpP^^*Www5W38".toCharArray()));
}
public static String removeDups(char []input){
long ocr1=0l,ocr2=0l,ocr3=0;
int index=0;
for(int i=0;i<input.length;i++){
int val=input[i]-(char)0;
long ocr=val<126?val<63?ocr1:ocr2:ocr3;
if((ocr& (1l<<val))==0){//not duplicate
input[index]=input[i];
index++;
}
if(val<63)
ocr1|=(1l<<val);
else if(val<126)
ocr2|=(1l<<val);
else
ocr3|=(1l<<val);
}
return new String(input,0,index);
}
please keep in mind that each of orc(s) represent a mapping of a range of ASCII characters and each java long variable can grow as big as (2^63) and since we have 128 characters in ASCII so we need three ocr(s) which basically maps the occurrences of the character to a long number.
ocr1: (char)0 to (char)62
ocr2: (char)63 to (char)125
ocr3: (char)126 to (char)128
Now if a duplicate was found the
(ocr& (1l<<val))
will be greater than zero and we skip that char and finally we can create a new string with the size of index which shows last non duplicate items index.
You can define more orc(s) and support other character-sets if you want.
Can use HashSet as well as normal for loops:
public class RemoveDupliBuffer
{
public static String checkDuplicateNoHash(String myStr)
{
if(myStr == null)
return null;
if(myStr.length() <= 1)
return myStr;
char[] myStrChar = myStr.toCharArray();
HashSet myHash = new HashSet(myStrChar.length);
myStr = "";
for(int i=0; i < myStrChar.length ; i++)
{
if(! myHash.add(myStrChar[i]))
{
}else{
myStr += myStrChar[i];
}
}
return myStr;
}
public static String checkDuplicateNo(String myStr)
{
// null check
if (myStr == null)
return null;
if (myStr.length() <= 1)
return myStr;
char[] myChar = myStr.toCharArray();
myStr = "";
int tail = 0;
int j = 0;
for (int i = 0; i < myChar.length; i++)
{
for (j = 0; j < tail; j++)
{
if (myChar[i] == myChar[j])
{
break;
}
}
if (j == tail)
{
myStr += myChar[i];
tail++;
}
}
return myStr;
}
public static void main(String[] args) {
String myStr = "This is your String";
myStr = checkDuplicateNo(myStr);
System.out.println(myStr);
}
Try this simple answer- works well for simple character string accepted as user input:
import java.util.Scanner;
public class string_duplicate_char {
String final_string = "";
public void inputString() {
//accept string input from user
Scanner user_input = new Scanner(System.in);
System.out.println("Enter a String to remove duplicate Characters : \t");
String input = user_input.next();
user_input.close();
//convert string to char array
char[] StringArray = input.toCharArray();
int StringArray_length = StringArray.length;
if (StringArray_length < 2) {
System.out.println("\nThe string with no duplicates is: "
+ StringArray[1] + "\n");
} else {
//iterate over all elements in the array
for (int i = 0; i < StringArray_length; i++) {
for (int j = i + 1; j < StringArray_length; j++) {
if (StringArray[i] == StringArray[j]) {
int temp = j;//set duplicate element index
//delete the duplicate element by copying the adjacent elements by one place
for (int k = temp; k < StringArray_length - 1; k++) {
StringArray[k] = StringArray[k + 1];
}
j++;
StringArray_length--;//reduce char array length
}
}
}
}
System.out.println("\nThe string with no duplicates is: \t");
//print the resultant string with no duplicates
for (int x = 0; x < StringArray_length; x++) {
String temp= new StringBuilder().append(StringArray[x]).toString();
final_string=final_string+temp;
}
System.out.println(final_string);
}
public static void main(String args[]) {
string_duplicate_char object = new string_duplicate_char();
object.inputString();
}
}
Another easy solution to clip the duplicate elements in a string using HashSet and ArrayList :
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
public class sample_work {
public static void main(String args[]) {
String input = "";
System.out.println("Enter string to remove duplicates: \t");
Scanner in = new Scanner(System.in);
input = in.next();
in.close();
ArrayList<Character> String_array = new ArrayList<Character>();
for (char element : input.toCharArray()) {
String_array.add(element);
}
HashSet<Character> charset = new HashSet<Character>();
int array_len = String_array.size();
System.out.println("\nLength of array = " + array_len);
if (String_array != null && array_len > 0) {
Iterator<Character> itr = String_array.iterator();
while (itr.hasNext()) {
Character c = (Character) itr.next();
if (charset.add(c)) {
} else {
itr.remove();
array_len--;
}
}
}
System.out.println("\nThe new string with no duplicates: \t");
for (int i = 0; i < array_len; i++) {
System.out.println(String_array.get(i).toString());
}
}
}
your can use this simple code and understand how to remove duplicates values from string.I think this is the simplest way to understand this problem.
class RemoveDup
{
static int l;
public String dup(String str)
{
l=str.length();
System.out.println("length"+l);
char[] c=str.toCharArray();
for(int i=0;i<l;i++)
{
for(int j=0;j<l;j++)
{
if(i!=j)
{
if(c[i]==c[j])
{
l--;
for(int k=j;k<l;k++)
{
c[k]=c[k+1];
}
j--;
}
}
}
}
System.out.println("after concatination lenght:"+l);
StringBuilder sd=new StringBuilder();
for(int i=0;i<l;i++)
{
sd.append(c[i]);
}
str=sd.toString();
return str;
}
public static void main(String[] ar)
{
RemoveDup obj=new RemoveDup();
Scanner sc=new Scanner(System.in);
String st,t;
System.out.println("enter name:");
st=sc.nextLine();
sc.close();
t=obj.dup(st);
System.out.println(t);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication26;
import java.util.*;
/**
*
* #author THENNARASU
*/
public class JavaApplication26 {
public static void main(String[] args) {
int i,j,k=0,count=0,m;
char a[]=new char[10];
char b[]=new char[10];
Scanner ob=new Scanner(System.in);
String str;
str=ob.next();
a=str.toCharArray();
int c=str.length();
for(j=0;j<c;j++)
{
for(i=0;i<j;i++)
{
if(a[i]==a[j])
{
count=1;
}
}
if(count==0)
{
b[k++]=a[i];
}
count=0;
}
for(m=0;b[m]!='\0';m++)
{
System.out.println(b[m]);
}
}
}
i wrote this program. Am using 2 char arrays instead. You can define the number of duplicate chars you want to eliminate from the original string and also shows the number of occurances of each character in the string.
public String removeMultipleOcuranceOfChar(String string, int numberOfChars){
char[] word1 = string.toCharArray();
char[] word2 = string.toCharArray();
int count=0;
StringBuilder builderNoDups = new StringBuilder();
StringBuilder builderDups = new StringBuilder();
for(char x: word1){
for(char y : word2){
if (x==y){
count++;
}//end if
}//end inner loop
System.out.println(x + " occurance: " + count );
if (count ==numberOfChars){
builderNoDups.append(x);
}else{
builderDups.append(x);
}//end if else
count = 0;
}//end outer loop
return String.format("Number of identical chars to be in or out of input string: "
+ "%d\nOriginal word: %s\nWith only %d identical chars: %s\n"
+ "without %d identical chars: %s",
numberOfChars,string,numberOfChars, builderNoDups.toString(),numberOfChars,builderDups.toString());
}
Try this simple solution for REMOVING DUPLICATE CHARACTERS/LETTERS FROM GIVEN STRING
import java.util.Scanner;
public class RemoveDuplicateLetters {
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
System.out.println("enter a String:");
String s=scn.nextLine();
String ans="";
while(s.length()>0)
{
char ch = s.charAt(0);
ans+= ch;
s = s.replace(ch+"",""); //Replacing all occurrence of the current character by a spaces
}
System.out.println("after removing all duplicate letters:"+ans);
}
}
In Java 8 we can do that using
private void removeduplicatecharactersfromstring() {
String myString = "aabcd eeffff ghjkjkl";
StringBuilder builder = new StringBuilder();
Arrays.asList(myString.split(" "))
.forEach(s -> {
builder.append(Stream.of(s.split(""))
.distinct().collect(Collectors.joining()).concat(" "));
});
System.out.println(builder); // abcd ef ghjkl
}

Java String Bubble Sorting

I need help sorting this array in alphabetical order using the bubble sort algorithm.
My code is:
public class Strings
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
String tempStr;
System.out.print("Enter the strings > ");
String s1 = new String(reader.nextLine());
String[] t1 = s1.split(", ");
for (int t=0; t<t1.length-1; t++)
{
for (int i = 0; i<t1.length -1; i++)
{
if(t1[i+1].compareTo(t1[1+1])>0)
{
tempStr = t1[i];
t1[i] = t1[i+1];
t1[i+1] = tempStr;
}
}
}
for(int i=0;i<t1.length;i++)
{
System.out.println(t1[i]);
}
}
}
The code compiles, but it does not sort alphabetical. Please help me.
You have three errors in your code.
The first error is in the inner for loop, in the place where you do the check statement, it should be i < t1.length - t -1 not i < t1.length -1. You subtract t because you do not want to loop through the whole array again, only the first part of it.
The second and third errors are in the if statement. You need to turn the greater than symbol into a lesser than symbol, because the way you have the compareTo method set up, it will return a negative number.
The other error in this line is that in the compareTo parameter you put 1 + 1 it actually should be just i, because you want one less than the object it is comparing to.
The fixed working code is below (Comments are what you originally had):
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String tempStr;
System.out.print("Enter the strings > ");
String s1 = new String(reader.nextLine());
String[] t1 = s1.split(", ");
for (int t = 0; t < t1.length - 1; t++) {
for (int i= 0; i < t1.length - t -1; i++) {
if(t1[i+1].compareTo(t1[i])<0) {
tempStr = t1[i];
t1[i] = t1[i + 1];
t1[i + 1] = tempStr;
}
}
}
for (int i = 0; i < t1.length; i++) {
System.out.println(t1[i]);
}
}
please change
String[] t1 = s1.split(", ");
to
String[] t1 = s1.split("");
This will solve the issue.

Categories