Reduction of duplicate words prior to uppercase or lowercase - java

Main
public class Main
{
public static void main(String[] args)
{
System.out.println(Dupe.Eliminate("Testing UppeR and loweR"));
System.out.println(Dupe.Eliminate("UppeR is BetteR"));
}
}
Class
public class Dupe
{
public static String Eliminate(String input)
{
char[] chrArray = input.toCharArray();
String letter ="";
for (char value:chrArray){
if (letter.indexOf(value) == -1){
letter += value;
}
}
return letter;
}
}
I am trying to eliminate duplicate letters e.g. Hello would be Helo. Which I have achieved, however, what I want to implement is that it won't matter if it's uppercase or lowercase, it will still be classed as a duplicate so Hehe would be He, not Heh. Should I .equals... each individual letter or is there an efficient way? sorry for asking if it's simple question for you guys.

This is how I would approach this. This might not be the most efficient way to do it, but you can try this.
public class Main
{
public static void main(String[] args)
{
System.out.println(Dupe.Eliminate("Testing UppeR and loweR"));
}
}
class Dupe
{
public static String Eliminate(String input)
{
char[] chrArray = input.toCharArray();
String letter ="";
for(int index = 0; index < chrArray.length; index++)
{
int j = 0;
boolean flag = true;
//this while loop is used to check if the next character is already existed in the string (ignoring the uppercase or lowercase)
while(j < letter.length())
{
if((int)chrArray[index] == letter.charAt(j) || (int)chrArray[index] == ((int)letter.charAt(j)+32) ) //32 is because the difference between the ascii value of the uppercase and lowercase letter is 32
{
flag = false;
break;
}
else
j++;
}
if(flag == true)
{
letter += chrArray[index];
}
}
return letter;
}
}

you can have 2 checks in place with upper case and lower case characters:
public static String Eliminate(String input)
{
char[] chrArray = input.toCharArray();
String letter ="";
for (char value:chrArray){
if (letter.indexOf(value.toLowerCase()) == -1 && letter.indexOf(value.toUpperCase()) == -1){
letter += value;
}
}
return letter;
}

Here you go, this will replace all duplicate characters no matter how many in the sequence.
public static void main(String[] args)
{
String duped = "aaabbccddeeffgg";
final Pattern p = Pattern.compile("(\\w)\\1+");
final Matcher m = p.matcher(duped);
while (m.find())
System.out.println("Duplicate character " + (duped = duped.replaceAll(m.group(), m.group(1))));
}
If you are looking for duplicates like: abacd to replace both a's, try this as the regex given in Pattern.compile(".*([0-9A-Za-z])\\1+.*")

Here's another (stateful) way to do it:-
String s = "Hehe";
Set<String> found = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
String result = s.chars()
.mapToObj(c -> "" + (char) c)
.filter(found::add)
.collect(Collectors.joining());
System.out.println(result);
Output: He

Related

Reverse words without changing capitals or punctuation

Create a program with the lowest amount of characters to reverse each word in a string while keeping the order of the words, as well as punctuation and capital letters, in their initial place.
By "Order of the words", I mean that each word is split by an empty space (" "), so contractions and such will be treated as one word. The apostrophe in contractions should stay in the same place. ("Don't" => "Tno'd").
(Punctuation means any characters that are not a-z, A-Z or whitespace*).
Numbers were removed from this list due to the fact that you cannot have capital numbers. Numbers are now treated as punctuation.
For example, for the input:
Hello, I am a fish.
it should output:
Olleh, I ma a hsif.
Notice that O, which is the first letter in the first word, is now capital, since H was capital before in the same location.
The comma and the period are also in the same place.
More examples:
This; Is Some Text!
would output
Siht; Si Emos Txet!
I've tried this:
public static String reverseWord(String input)
{
String words[]=input.split(" ");
StringBuilder result=new StringBuilder();
for (String string : words) {
String revStr = new StringBuilder(string).reverse().toString();
result.append(revStr).append(" ");
}
return result.toString().trim();
}
I have tried to solve your problem. It's working fine for the examples I have checked :) Please look and let me know :)
public static void main(String[] args) {
System.out.println(reverseWord("This; Is Some Text!"));
}
public static boolean isAlphaNumeric(String s) {
return s != null && s.matches("^[a-zA-Z0-9]*$");
}
public static String reverseWord(String input)
{
String words[]=input.split(" ");
StringBuilder result=new StringBuilder();
int startIndex = 0;
int endIndex = 0;
for(int i = 0 ; i < input.length(); i++) {
if (isAlphaNumeric(Character.toString(input.charAt(i)))) {
endIndex++;
} else {
String string = input.substring(startIndex, endIndex);
startIndex = ++endIndex;
StringBuilder revStr = new StringBuilder("");
for (int j = 0; j < string.length(); j++) {
char charToAdd = string.charAt(string.length() - j - 1);
if (Character.isUpperCase(string.charAt(j))) {
revStr.append(Character.toUpperCase(charToAdd));
} else {
revStr.append(Character.toLowerCase(charToAdd));
}
}
result.append(revStr);
result.append(input.charAt(i));
}
}
if(endIndex>startIndex) // endIndex != startIndex
{
String string = input.substring(startIndex, endIndex);
result.append(string);
}
return result.toString().trim();
}
Call the reverseWord with your test string.
Hope it helps. Don't forget to mark it as right answer, if it is :)
Here is a proposal that follows your requirements. It may seem very long but its just comments and aerated code; and everybody loves comments.
public static String smartReverseWords(String input) {
StringBuilder finalString = new StringBuilder();
// Word accumulator, resetted after each "punctuation" (or anything different than a letter)
StringBuilder wordAcc = new StringBuilder();
int processedChars = 0;
for(char c : input.toCharArray()) {
// If not a whitespace nor the last character
if(!Character.isWhitespace(c)) {
// Accumulate letters
wordAcc.append(c);
// Have I reached the last character? Then finalize now:
if(processedChars == input.length()-1) {
reverseWordAndAppend(wordAcc, finalString);
}
}
else {
// Was a word accumulated?
if(wordAcc.length() > 0) {
reverseWordAndAppend(wordAcc, finalString);
}
// Append non-letter char to final string:
finalString.append(c);
}
processedChars++;
}
return finalString.toString();
}
private static void reverseWordAndAppend(StringBuilder wordAcc, StringBuilder finalString) {
// Then reverse it:
smartReverse(wordAcc); // a simple wordAcc.reverse() is not possible
// Append word to final string:
finalString.append(wordAcc.toString());
// Reset accumulator
wordAcc.setLength(0);
}
private static class Marker {
Integer position;
String character;
}
private static void smartReverse(StringBuilder wordAcc) {
char[] arr = wordAcc.toString().toCharArray();
wordAcc.setLength(0); // clean it for now
// Memorize positions of 'punctuation' + build array free of 'punctuation' in the same time:
List<Marker> mappedPosOfNonLetters = new ArrayList<>(); // order matters
List<Integer> mappedPosOfCapitals = new ArrayList<>(); // order matters
for (int i = 0; i < arr.length; i++) {
char c = arr[i];
if(!Character.isLetter(c)) {
Marker mark = new Marker();
mark.position = i;
mark.character = c+"";
mappedPosOfNonLetters.add(mark);
}
else {
if(Character.isUpperCase(c)) {
mappedPosOfCapitals.add(i);
}
wordAcc.append(Character.toLowerCase(c));
}
}
// Reverse cleansed word:
wordAcc.reverse();
// Reintroduce 'punctuation' at right place(s)
for (Marker mark : mappedPosOfNonLetters) {
wordAcc.insert(mark.position, mark.character);
}
// Restore capitals at right place(s)
for (Integer idx : mappedPosOfCapitals) {
wordAcc.setCharAt(idx,Character.toUpperCase(wordAcc.charAt(idx)));
}
}
EDIT
I've updated the code to take all your requirements into account. Indeed we have to make sure that "punctuation' stay in place (and capitals also) but also within a word, like a contraction.
Therefore given the following input string:
"Hello, I am on StackOverflow. Don't tell anyone."
The code produces this output:
"Olleh, I ma no WolfrEvokcats. Tno'd llet enoyna."

Replace characters within a string using the java replace method

Im a beginner java programmer and I am stuck on a little problem with my university coursework.
Basically I have a string that I want to iterate through and replace all instances of the letter 'a' or 'e' with the letter 'z'. For example, if the original string was "hello alan", the final string should be "hzllo zlzn".
We need to do this using a character array which holds the characters 'a' and 'e' to test against the string.
I've included my code below, we need to use the charAt() method also.
public static void main(String[] args) {
String a = ("what's the craic?");
char letters[] = new char[]{'a', 't'};
System.out.println("Before:" + a);
System.out.println("After: " + removeCharacters(a, letters));
}
public static String removeCharacters(String sentence, char[] letters) {
for (int i = 0; i < sentence.length(); i++) {
for (int j = 0; j < letters.length; j++) {
if (sentence.charAt(i) == letters[j]) {
sentence = sentence.replace(sentence.charAt(i), 'z');
} else {
sentence = "No changes nessesary";
}
}
}
return sentence;
}
Please help me with this problem. Im not sure where I am going wrong! Thanks.
if You are allowed to use replaceAll as well
"hello alan".replaceAll( "[ae]", "z" ); // hzllo zlzn
In difference to replace uses replaceAll a Pattern internally, which is compiled from the first argument [ae] to find the part to substitute with the second argument z. This solution is elegantly short, but slow, because the Pattern has to be compiled each time replaceAll is called.
otherwise use a StringBuilder
char[] letters = new char[] { 'a', 'e' };
StringBuilder buf = new StringBuilder( "hello alan" );
IntStream.range( 0, buf.length() ).forEach( i -> {
for( char c : letters )
if( buf.charAt( i ) == c )
buf.replace( i, i + 1, "z" );
} );
String s = buf.toString(); // hzllo zlzn
In difference to a String the contents of a StringBuilder is mutual (means you can change it). So it only has to be created once and all substitutions can be made in place.
Try this:
public static void main(String[] args) {
String a = "hello alan";
System.out.println("Before:" + a);
System.out.println("After: " + removeCharacters(a));
}
public static String removeCharacters(String sentence) {
if (!sentence.contains("a|e"))
return "No changes necessary";
return sentence.replaceAll("a|e", "z");
}
output 1:
Before:hello alan
After: hzllo zlzn
output 2:
Before:hi world
After: No changes necessary
Since you're forced to use charAt(...), one way would be like this:
public static String removeCharacters(String sentence, char[] letters) {
String output = "";
boolean wasChanged = false;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
for (int j = 0; j < letters.length; j++)
if (ch == letters[j]) {
ch = 'z';
wasChanged = true;
break;
}
output += ch;
}
if (wasChanged)
return output;
else
return "No changes necessary";
}
Since String::replace(char oldChar, char newChar) returns a new string resulting from replacing all occurrences of oldChar in this string with newChar, you do not need nested loops to do it. An efficient way of doing it can be as follows:
public static String removeCharacters(String sentence, char[] letters) {
String copy = sentence;
for (char letter : letters) {
sentence = sentence.replace(letter, 'z');
}
if (sentence.equals(copy)) {
sentence = "No changes nessesary";
}
return sentence;
}
Demo:
public class Main {
public static void main(String[] args) {
// Test
System.out.println(removeCharacters("hello stackoverflow", new char[] { 'a', 'e' }));
System.out.println(removeCharacters("world", new char[] { 'a', 'e' }));
}
public static String removeCharacters(String sentence, char[] letters) {
String copy = sentence;
for (char letter : letters) {
sentence = sentence.replace(letter, 'z');
}
if (sentence.equals(copy)) {
sentence = "No changes nessesary";
}
return sentence;
}
}
Output:
hzllo stzckovzrflow
No changes nessesary

How to get each letter and add them as points with a substring method

I've been trying to create an algorithm where each letter adds points. I don't want to use charAt, I'd like to use the substring method.
My problem is that String letter does not seem to get each letter and the result is always 0.
Is there a way to get each letter and convert it to points?
public class WDLPoints{
public static void main(String[] args){
String word = "LDWWL";
System.out.println(getMatchPoints(word));
}
public static int getMatchPoints(String word) {
int points = 0;
String letter = word.substring(5);
for (int i = 0; i < word.length(); i++) {
if (letter.equals("W")) {
points+=3;
}
else if (letter.equals("D")) {
points+=1;
}
else {
points = 0;
}
}
return points;
}
}
You may try the following changes in your public static int getMatchPoints(String word) method:
for (int i = 0; i < word.length(); i++) {
String letter = word.substring(i, i + 1);
if (letter.equals("W")) {
points+=3;
}
else if (letter.equals("D")) {
points+=1;
}
}
word.substring(i, i + 1) will get a single letter word and will help you compute your score the way you want.
If you want to make it really simple you can just use String.toCharArray() and then iterate over the array of char and check its value:
public static int getMatchPoints(String word) {
int points = 0;
char[] arr = word.toCharArray();
for (char letter : arr) {
if (letter == 'W') {
points += 3;
}
else if (letter == 'D') {
points += 1;
}
}
return points;
}
I also removed your else statement because that was just setting the value to 0 if there is any other letter in the loop. I think you intended it to be points += 0 which does nothing, so it can just be removed.
Example Run:
Input:
String word = "LDWWL";
Output:
7
Note: I am aware you might not be allowed to use this solution, but I thought it would be good info on the possibilities since it does not technically use charAt()
Also I'd like to point out you misunderstand what substring(5) does. This will return all characters after the position of 5 as a single String, it does not separate the String into different characters or anything.
You will find that your variable letter is always the empty String. Here's a better way of doing things:
class WDLPoints
{
public static void main(String[] args)
{
String word = "LDWWL";
System.out.println(getMatchPoints(word));
}
// We have only one method to encode character values, all in one place
public static int getValueForChar(int c)
{
switch((char)c)
{
case 'W': return 3;
case 'D': return 1;
default: return 0; //all non-'W's and non-'D's are worth nothing
}
}
public static int getMatchPoints(String word)
{
// for all the characters in the word
return word.chars()
// get their integer values
.map(WDLPoints::getValueForChar)
// and sum all the values
.sum();
}
}
Assuming your string represents a football teams performance of the last 5 games, you could keep it simple and readable with something like:
public static int getMatchPoints(String word) {
String converted = word.replace('W', '3').replace('D', '1').replace('L', '0');
return converted.chars().map(Character::getNumericValue).sum();
}
This converts your example input "LDWWL" to "01330" and sums each char by getting its numeric value.

Best way to check if String is in alphabetical order?

This is the most intuitive way to check if a five character String is in alphabetical order?
String newStr = "Hello";
if (newStr.charAt(0) <= newStr.charAt(1) &&
newStr.charAt(1) <= newStr.charAt(2) &&
newStr.charAt(2) <= newStr.charAt(3) &&
newStr.charAt(3) <= newStr.charAt(4)) {
System.out.println("In order");
} else
System.out.println("NOT in order");
You can try this
public static void main(String[] args) {
String str = "Hello";
char[] newStr = str.toCharArray();
char previous = '\u0000';
isInOrder(previous,newStr);
}
private static boolean isInOrder(char previous, char[] arr) {
for (char current : arr) {
if (current < previous)
return false;
previous = current;
}
return true;
}
In your case this might be good enough.
But think of it as you want to do this to Strings longer than five characters... than it will be a very long if-statement and much more work to do.
I'd rather suggest to use a loop, then you dont need to fix the length of your String.
I.e.
boolean sorted = true;
for(int i = 0; i < newStr.length()-1; i++){
if(newStr.charAt(i) >= newStr.charAt(i+1)){
sorted = false;
break;
}
}
if(sorted){
System.out.println("In order");
}else{
System.out.println("NOT in order");
}
You may use Regular Expression like below :
public boolean checkString(String str)
{
String str = "^a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z*$";
Pattern pattern = null;
Matcher matcher;
try{
pattern = Pattern.compile(str,Pattern.CASE_INSENSITIVE);
System.out.println(matcher.matches());*/
matcher = pattern.matcher("Hello");
return matcher.matches();
}
catch(Exception ex){
ex.printStackTrace();
return false;
}
}
Your Main class or from where you call above function :
String myStr = "Hello";
boolean isAlphaOrder = checkString(myStr);
if(isAlphaOrder)
System.out.println("String is in order");
else
System.out.println("NOT in order");
If you are looking for the most simplest one, then perhaps this is what you are looking for:
public static void main(String[] args) {
String str = "Hello";
System.out.println(alphabeticalOrder(str.toLowerCase()));
}
public static boolean alphabeticalOrder(String str){
for(int i = 0;i<str.length()-1;i++)
if(str.charAt(i) > str.charAt(i+1))
return false;
return true;
}
You have to be aware that letter in capital have not the same index that their letter not in capital.
So if you want that abcDe return true, you should also use a tempory String to do you check like this :
String yourString ="..."
String tmp = yourString.toLowerCase();
boolean isInOrder = testYourString(tmp);
you may want this:
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="Hello";
str=str.toLowerCase();
char[] ch=str.toCharArray();
Arrays.sort(ch);
String str1="";
for(int i=0;i<ch.length;i++)
{
str1+=ch[i]+"";
}
if(str1.equals(str))
{
System.out.println("In order");
}
else
{
System.out.println("NOT in order");
}
}
It seems that the logic needs to be improved
for input String "AbCd" & HeLLo code is printing not in order
You have tried to compare the ascii values of characters and you know that for
same case letters (lower Case or Upper Case) ascii values would be in increasing order.
Hence your logic stays intact if input string is in same case :
e.g. "hello" ,"HELLO", "abcd" or "ABCD"
If you are using string with Mixed Case letters then it wont work correctly.

Alternating string of characters and digits

I was given this problem to solve. I have only the slightest idea on how it should be implemented, and I'm all too new with programming and stuffs, and would love to hear your comments on this.
Say given a string in the form "abc1234defgh567jk89", and I must create a new string "a1b2c3d5e6f7j8k9".
Note that there are corresponding [digits] & [characters] group and since there may be more of one type over the other, the output has only matching sequence and ignore extra digits or characters in this case '4' & 'g' & 'h'.
I know I will have to use 2 sets of queues to store both types of elements, but I do not know how else to proceed from here.
Would appreciate if you could share a pseudocode or a Java(prefably) version, since I am learning thru this language now.
Thank you.
Pseudocode:
Queue letterQueue;
Queue numberQueue;
for (every character in the string) {
if (it's a letter) {
if (numberQueue is not empty) {
add the letters alternating into the buffer (stringbuilder), and purge buffers
}
add newest letter to letterqueue
}
if (it's a number) {
add newest letter to numberqueue
}
}
add any remaining unprocessed letters to the queue (this will happen most of the time)
return contents of string buffer
You will need:
Queue, probably a LinkedList
StringBuilder
String.toCharArray
Character
Code:
import java.util.LinkedList;
import java.util.Queue;
public class StringTest {
private static String str ="abc1234defgh567jk89";
private static String reorganize(String str) {
Queue<Character> letterQueue = new LinkedList<>();
Queue<Character> numberQueue = new LinkedList<>();
StringBuilder s = new StringBuilder();
for (char c : str.toCharArray()) {
if(Character.isLetter(c)) {
if (!numberQueue.isEmpty()) processQueues(letterQueue, numberQueue, s);
letterQueue.offer(c);
} else if(Character.isDigit(c)) {
numberQueue.offer(c);
}
}
processQueues(letterQueue, numberQueue, s);
return s.toString();
}
private static void processQueues(Queue<Character> letterQueue, Queue<Character> numberQueue, StringBuilder s) {
while(!letterQueue.isEmpty() && !numberQueue.isEmpty()) {
s.append(letterQueue.poll());
s.append(numberQueue.poll());
}
letterQueue.clear();
numberQueue.clear();
}
public static void main(String... args) {
System.out.println(reorganize(str));
}
}
See this hint:
String str = "abc1234defgh567jk89";
String c = str.replaceAll("\\d", ""); // to store characters
String d = str.replaceAll("\\D", ""); // to store digits
Try this:
public static void main(String[] args) {
String str = "abc1234defgh567jk89";
String c = str.replaceAll("\\d", "");
String d = str.replaceAll("\\D", "");
String result = "";
int j = 0, k = 0;
int max = Math.max(c.length(), d.length());
for (int i = 0; i < max; i++) {
if (j++ < c.length())
result = result + c.charAt(i);
if (k++ < d.length())
result = result + d.charAt(i);
}
System.out.println(result);
}
Output:
a1b2c3d4e5f6g7h8j9k

Categories

Resources