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
Related
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."
I have a string in format AB123. I want to split it between the AB and 123 so AB123 becomes AB 123. The contents of the string can differ but the format stays the same. Is there a way to do this?
Following up with the latest information you provided (2 letters then 3 numbers):
myString.subString(0, 2) + " " + myString.subString(2)
What this does: you split your input string myString at the 2nd character and append a space at this position.
Explanation: \D represents non-digit and \d represents a digit in a regular expression and I used ternary operation in the regex to split charter to the number.
String string = "AB123";
String[] split = string.split("(?<=\\D)(?=\\d)");
System.out.println(split[0]+" "+split[1]);
Try
String a = "abcd1234";
int i;
for(i = 0; i < a.length(); i++){
char c = a.charAt(i);
if( '0' <= c && c <= '9' )
break;
}
String alphaPart = a.substring(0, i);
String numberPart = a.substring(i);
Hope this helps
Although I would personally use the method provided in #RakeshMothukur's answer, since it also works when the letter or digit counts increase/decrease later on, I wanted to provide an additional method to insert the space between the two letters and three digits:
String str = "AB123";
StringBuilder sb = new StringBuilder(str);
sb.insert(2, " "); // Insert a space at 0-based index 2; a.k.a. after the first 2 characters
String result = sb.toString(); // Convert the StringBuilder back to a String
Try it online.
Here you go. I wrote it in very simple way to make things clear.
What it does is : After it takes user input, it converts the string into Char array and it checks single character if its INT or non INT.
In each iteration it compares the data type with the prev character and prints accordingly.
Alternate Solutions
1) Using ASCII range (difficulty = easy)
2) Override a method and check 2 variables at a time. (difficulty = Intermediate)
import org.omg.CORBA.INTERNAL;
import java.io.InputStreamReader;
import java.util.*;
import java.io.BufferedReader;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char[] s = br.readLine().toCharArray();
int prevflag, flag = 0;
for (int i = 0; i < s.length; i++) {
int a = Character.getNumericValue(s[i]);
String b = String.valueOf(s[i]);
prevflag = flag;
flag = checktype(a, b);
if ((prevflag == flag) || (i == 0))
System.out.print(s[i]);
else
System.out.print(" " + s[i]);
}
}
public static int checktype(int x, String y) {
int flag = 0;
if (String.valueOf(x).equals(y))
flag = 1; // INT
else
flag = 2; // non INT
return flag;
}
}
I was waiting for a compile to finish before heading out, so threw together a slightly over-engineered example with basic error checking and a test.
import java.text.ParseException;
import java.util.LinkedList;
public class Main {
static public class ParsedData {
public final String prefix;
public final Integer number;
public ParsedData(String _prefix, Integer _number) {
prefix = _prefix;
number = _number;
}
#Override
public String toString() {
return prefix + "\t" + number.toString();
}
}
static final String TEST_DATA[] = {"AB123", "JX7272", "FX402", "ADF123", "JD3Q2", "QB778"};
public static void main(String[] args) {
parseDataArray(TEST_DATA);
}
public static ParsedData[] parseDataArray(String[] inputs) {
LinkedList<ParsedData> results = new LinkedList<ParsedData>();
for (String s : TEST_DATA) {
try {
System.out.println("Parsing: " + s);
if (s.length() != 5) throw new ParseException("Input Length incorrect: " + s.length(), 0);
String _prefix = s.substring(0, 2);
Integer _num = Integer.parseInt(s.substring(2));
results.add(new ParsedData(_prefix, _num));
} catch (ParseException | NumberFormatException e) {
System.out.printf("\"%s\", %s\n", s, e.toString());
}
}
return results.toArray(new ParsedData[results.size()]);
}
}
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
I'm trying to work out a way of splitting up a string in java that follows a pattern like so:
String a = "24ab4h";
The results from this should be the following:
st[0] = "24";
st[1] = "a";
st[2] = "b";
st[3] = "4";
st[4] = "h";
However, I'm completely stumped as to how I can achieve this. Please, can someone help me out? I have tried searching online for a similar problem, however, it's very difficult to phrase it correctly in a search.
If you use a split() function you'll loose the elements which are used as delimiters so I think use a Pattern is better :
public static void main(String args[]) {
Matcher m = Pattern.compile("\\d+|[a-zA-Z]").matcher("24ab4h");
List<String> res = new ArrayList<>();
while (m.find()) {
res.add(m.group());
}
}
The pattern will detect all group of digits OR alpabet char alone, then it will add all into a List (better than array because you don't know the size)
If you really want an array at the end, 2 solutions for List<String> ->String[] :
String[] array = res.toArray(new String[res.size()]);
String[] array = res.stream().toArray(String[]::new);
Try to process your String in a loop, char by char.
String a = "24ab4h";
If focused char (2) is number - check next char (4). If next char is also a number - continue scanning. If next char differs from number - save focused char (or focused char sequence, in this example it is - 24).
The same logic for alphabet chars.
public static void main(String[] args) {
/*
* Stack stack = new Stack(5); stack.push("10"); stack.push("20");
* stack.push("20"); stack.push("20"); stack.push("20");
* stack.push("20"); stack.push("20"); stack.displayStack();
*/
String a = "24ab4h";
System.out.println(Arrays.deepToString(splitString(a)));
}
private static String[] splitString(String a) {
char[] result = new char[a.length()];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < a.length(); i++) {
if (isNumber(a.charAt(i))) {
if (i != 0 && !isNumber(a.charAt(i - 1)))
sb.append(" ");
sb.append(a.charAt(i));
} else {
sb.append(" ");
sb.append(a.charAt(i));
}
}
return sb.toString().split(" ");
}
private static boolean isNumber(char c) {
try {
Integer i = Integer.parseInt(String.valueOf(c));
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
How could I replace the letters in a String such as "Hello", with the letters here?
String bubbled = "ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ";
I was initially just doing a replaceAll ("a","ⓐ"), but I feel like there has to be a more efficient way of doing this.
Split bubbled into lowercase and uppercase. Make a new StringBuilder, iterate over each char of source, and if chr >= 'a' && chr <= 'z' append lowercaseBubbled[chr - 'a'], if it's in uppercase range do similar, else just append chr. At the end, use toString on the builder.
Or you could use a slightly less efficient method, replaceChars (since it has to use indexOf) found in Apache Commons. Pro: it's a library, so no extra work for you.
You could use the characters a and ⓐ to determine the offset values for the alphabet. In combination with a StringBuilder it should be rather efficient. Of course you would likely have to be very strict about the input string being only alphabet characters.
This is the code for what I described above:
public class Bubbled {
public static void main(String[] args) {
char bubbledA = 'ⓐ';
int lowerCaseOffset = bubbledA - 'a';
int upperCaseOffset = bubbledA - 'A';
String input = "Hello";
StringBuilder bubbledOutput = new StringBuilder();
for (Character c : input.toCharArray()) {
if (Character.isUpperCase(c)) {
bubbledOutput.append((char)(c + upperCaseOffset));
} else {
bubbledOutput.append((char)(c + lowerCaseOffset));
}
}
System.out.println(bubbledOutput.toString());
}
}
Output
ⓗⓔⓛⓛⓞ
Here is a code snipp that does it. It wont create a zillion String objects. I have only a smaller set of bubble chars just for demo purpose. Please tweak to your liking and no error handling has been done.
public class StackOverFlow {
private static int[] bubbled = {'ⓐ', 'ⓑ', 'ⓒ', 'ⓓ', 'ⓔ'};
private static int [] plain = {'a', 'b', 'c', 'd', 'e'};
private static Map<Integer, Integer> charMap = new HashMap<>();
public static void main(String[] args) {
String test = "adcbbceead";
for(int i=0; i<plain.length; i++) {
charMap.put(plain[i], bubbled[i]);
}
replaceWithBuffer(test);
}
private static void replaceWithBuffer(String test) {
System.out.println("Oginal String = " + test);
StringBuilder sb = new StringBuilder(test);
for(int i =0; i<test.length(); i++) {
int ch = sb.charAt(i);
char buubledChar = (char)charMap.get(ch).intValue();
sb.setCharAt(i, buubledChar);
}
System.out.println("New String = " + sb.toString());
}
}
Output:
Hope this helps :)
Use a for loop:
for (char i='a';i<'z';i++)
str = str.replaceAll(i,bubbled[i-'a']);
for (char i='A';i<'Z';i++)
str = str.replaceAll(i,bubbled[i-'A'+26]);
Of course, this wouldn't be too efficient, since Strings are immutable.