Swap escaped characters - java

I'm trying to swap the parentheses in the String A * (B + C) / D, but swapping them, results in A * \)B + C( / D instead of A * )B + C( / D.
public class InfixToPrefixExpression {
private String swapStrings(String expression, String one, String two){
return Arrays.stream(expression.split(one, -1))
.map(s -> s.replaceAll(two, one))
.collect(Collectors.joining(two));
}
public static void main(String[] args) {
String expression = "A * (B + C) / D";
String result = new InfixToPrefixExpression().swapStrings(expression,
"\\(","\\)");
System.out.println(result);
}
}
How do I remove the extra back-slash that appears in the resulting string? I tried the following as well, but the String.join() method adds the extra slash in the result.
// String[] split = expression.split(one, -1);
// for (int i = 0; i < split.length; i++) {
// split[i] = split[i].replaceAll(two, one);
// }
// String result = String.join(two, split);

An easy method of swapping may be to swap "(" for a special character like "_", then swap ")" for "(" and finally "_" for ")" like this:
final String expression = "A * (B + C) / D";
final String result = expression
.replace("(", "_")
.replace(")", "(")
.replace("_", ")");
If you don't want to use a special character, you can do a trick with splitting the expression by one bracket like this:
final String expression = "A * (B + C) / D";
final String[] substrings = expression.split("\\(");
final List<String> replacedSubstrings = new ArrayList<>();
for (String substring : substrings) {
replacedSubstrings.add(substring.replace(")","("));
}
final String result = String.join(")", replacedSubstrings);

You might need to provide special values to be used in regular expressions and in Collectors.joining:
private static String swapStrings(String expression, String one, String two){
String reOne = "\\" + one;
String reTwo = "\\" + two;
return Arrays.stream(expression.split(reOne, -1))
.map(s -> s.replaceAll(reTwo, one))
.collect(Collectors.joining(two));
}
Then this method may be called without escaping parentheses:
String expression = "A * (B + C) / D";
String result = swapStrings(expression, "(",")");
System.out.println(result);
Output:
A * )B + C( / D

Related

How would I remove letters at an even position throughout a string in Java?

String evensRemoved = "";
String str = reversedNames[1];
String noSpaces = str.replace(" ","");
int strlength = noSpaces.length();
for(int i = 0; i <= strlength; i++){
if(i % 2 == 0){
StringBuilder sb = new StringBuilder(noSpaces);
sb.deleteCharAt(i);
String result = sb.toString();
return result;
}
}
return "";
I want to be able to remove letters at even positions throughout the string completely, and then return the string to the original method. I've looked at other solutions and haven't been able to figure it out at all. New to Java.
Try this.
It uses a regex that takes two chars at a time and replaces them with the 2nd, thus removing every other one.
the (.) is a capture group of 1 character.
$1 is a back reference to it.
String s = "abcdefghijklmnopqrstuvwxyz";
s = s.replaceAll("(?s).(.)?", "$1");
System.out.println(s);
Prints
bdfhjlnprtvxz
per Andreas suggestion, I preceded the regex with a flag that lets . match returns and linefeeds.
To remove all characters at even indexes, copy all the characters at odd indexes to a new char[].
public static String removeEvens(String str) {
char[] buf = new char[str.length() / 2];
for (int i = 0; i < buf.length; i++)
buf[i] = str.charAt(i * 2 + 1);
return new String(buf);
}
Test
String str = "0123456789";
for (int i = 0; i <= str.length(); i++) {
String sub = str.substring(0, i);
System.out.println('"' + sub + "\" -> \"" + removeEvens(sub) + '"');
}
Output
"" -> ""
"0" -> ""
"01" -> "1"
"012" -> "1"
"0123" -> "13"
"01234" -> "13"
"012345" -> "135"
"0123456" -> "135"
"01234567" -> "1357"
"012345678" -> "1357"
"0123456789" -> "13579"

Replace fixed number of symbols in String

I have this number: 4200000000000000
I would like to leave only the first 4 digits and last 3 digits:
42000......000
Everything else should be replaced by dots. How I can implement this with some smart algorithm?
Why not use a StringBuilder and the substring method:
public static String foo(long num) {
String numToString = String.valueOf(num);
return new StringBuilder()
.append(numToString.substring(0 , 4))
.append("....")
.append(numToString.substring(numToString.length()-3, numToString.length()))
.toString();
}
When inputted 4200000000000000 it outputs:
4200....000
Or if the input is already a String:
public static String foo(String str) {
return new StringBuilder()
.append(str.substring(0 , 4))
.append("....")
.append(str.substring(str.length()-3, str.length()))
.toString();
}
Parse your number into a string and try this:
int last = 3;
int first = 4;
String number = '4200000000000000';
String start = number.substring(0,first-1);
String end = number.substring(number.length()-last,number.length()-1);
String dots = '';
for(int i = 0; i<number.length()-last-first;i++){
dots = dots + '.';
}
String result = start + dots + end;
You can use something like this,
public class Main {
public static void main(String[] args) {
System.out.println(convert("4200000000000000", 4, 3));
}
static String convert(String number, int firstDigits, int lastDigits) {
String first = number.substring(0, firstDigits);
String middle = number.substring(firstDigits, number.length() - lastDigits).replaceAll("0", ".");
String last = number.substring(number.length() - lastDigits, number.length());
return first + middle + last;
}
}
You could convert it to a char array, alter it, then convert it back into a string
char[] charArray = originalNumber.toCharArray();
for (int i; i < charArray.length; i++) {
if (i <= 4 || i >= charArray.length - 3) {
charArray[i] = ".";
}
}
String outputString = new String(charArray);
This will replace all chars from the 4th char up to the 4th from the end with '.':
String start = "4200000000000000";
System.out.println(start);
String target = start;
if (start.length() > 7) {
target = new StringBuilder()
.append(start.substring(0, 4))
.append(new String(new char[start.length() - 7]).replaceAll(".", "."))
.append(start.substring(start.length() - 3))
.toString();
}
System.out.println(target);
will print
4200000000000000
4200.........000
Using substring method of the String class :
String str = "4200000000000000";
String res = str.substring(0,4)+ str.substring(4,str.length()-3).replaceAll(".", ".") + str.substring(str.length()-3);
If you are using Apache commons library, you can use repeat method to create masking string of specified length and the overlay method of StringUtils class to overlay part of the String :
String str = "4200000000000000";
String mask= StringUtils.repeat('.', str.length()-7);
String res = StringUtils.overlay(str, mask, 4, str.length()-3);

How to center a string by formatting in Java?

I want my String to be formatted both from the left and right side, so it always keeps standing in the center.
Let's say I want the total length to be 30 symbols (let's mark spaces as stars to see clearly). I want the following result.
sampleString -> *********sampleString*********
sampleLongLongString -> *****sampleLongLongString*****
I tried to do the following.
result = padLeft("", 15) + padRight(myString, 15);
or
result = padLeft(padRight(myString, 15), 15);
For functions,
public static String padRight(String s, int n) {
return String.format("%1$-" + n + "s", s);
}
public static String padLeft(String s, int n) {
return String.format("%1$" + n + "s", s);
}
but no result.
You can create a method to add padding based on the length of the String.
Basically, you have to decide the total/max(left+right) padding for all the Strings. Please take a look at following method.
It also manages the space inside the String. Method will just return actual String if padding can not be added according to maxPadding.
public static String getPaddedString(String str, char paddingChar) {
if (str == null) {
throw new NullPointerException("Can not add padding in null String!");
}
int maxPadding = 20;//This is what you have to decide
int length = str.length();
int padding = (maxPadding - length) / 2;//decide left and right padding
if (padding <= 0) {
return str;// return actual String if padding is less than or equal to 0
}
String empty = "", hash = "#";//hash is used as a place holder
// extra character in case of String with even length
int extra = (length % 2 == 0) ? 1 : 0;
String leftPadding = "%" + padding + "s";
String rightPadding = "%" + (padding - extra) + "s";
String strFormat = leftPadding + "%s" + rightPadding;
String formattedString = String.format(strFormat, empty, hash, empty);
//Replace space with * and hash with provided String
String paddedString = formattedString.replace(' ', paddingChar).replace(hash, str);
return paddedString;
}
Following program proves that above method works,
public class Test {
public static void main(String args[]) {
System.out.println(getPaddedString("Hello", '*'));
System.out.println(getPaddedString("Hi23", '#'));
System.out.println(getPaddedString("Test. .Test", '%'));
System.out.println(getPaddedString(
"By the way, It's to long to fix !!", '*'));
}
}
OUTPUT
************Hello************
#############Hi23############
%%%%%%%%%Test. .Test%%%%%%%%%
By the way, It's to long to fix !!
Here's an easy-to-understand method to do it:
public static String center(String string, int length, char pad) {
StringBuilder sb = new StringBuilder(length);
sb.setLength((length - string.length()) / 2);
sb.append(string);
sb.setLength(length);
return sb.toString().replace('\0', pad);
}
With this code, when the total padding required is odd, the right-side padding has one extra pad char. To change the behaviour so that the left side gets the extra pad, change line 2 to:
sb.setLength((length - string.length() + 1) / 2);
This method will do the trick.
/**
* #param int w : length of the formatted string (e.g. 30)
* #param String s : the string to be formatted
* #param char c : character to pad with
* #param boolean pr: If s is odd, pad one extra left or right
* #return the original string, with pad 'p' on both sides
*/
private String pad(String s, int w, char c, boolean pr){
int pad = w-s.length();
String p = "";
for (int i=0; i<pad/2; i++)
p = p + c;
/* If s.length is odd */
if (pad%2 == 1)
/* Pad one extra either right or left */
if (pr) s = s + c;
else s = c + s;
return (p+s+p)
}

Java program to extract coefficents from quadratic equation

Problem: Java program to split the coefficients from a quadratic equation eg
if input string is:
String str1;
str1 = "4x2-4x-42=0"
So I need to split the coefficients from the given input string and to get output as
a = 4 b = -4 c = -42
I tried this:
String equation = "ax2+bx-c=0";
String[] parts = equation.split("\\+|-|=");
for (int i = 0; i < parts.length - 2; i++) {
String part = parts[i].toLowerCase();
System.out.println(part.substring(0, part.indexOf("x")));
}
System.out.println(parts[2]);
But I got the output as 23x2 and 4x and 4.
Actual output needed is 23 ,- 4 , 4.
Use Regex, the following pattern will work:
([+-]?\d+)[Xx]2\s*([+-]?\d+)[Xx]\s*([+-]?\d+)\s*=\s*0
This will match the quadratic and extract the parameters, lets work out how it works:
(...) this is capturing group
[+-]?\d+ this matches a number of digits, preceded optionally by a + or -
[Xx] this matches "X" or "x"
\s* this matches zero or more spaces
So
([+-]?\d+) matches the "a" argument
[Xx]2 matches "X2" or "x2"
\s* matches optional whitespace
([+-]?\d+) matches the "b" argument
[Xx] matches "X" or "x"
\s* matches optional whitespace
([+-]?\d+) matches the "c" argument
\s*=\s*0 matches "=0" with some optional spaces
Lets wrap this in a class:
private static final class QuadraticEq {
private static final Pattern EQN = Pattern.compile("([+-]?\\d+)[Xx]2\\s*([+-]?\\d+)[Xx]\\s*([+-]?\\d+)\\s*=\\s*0");
private final int a;
private final int b;
private final int c;
private QuadraticEq(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
public static QuadraticEq parseString(final String eq) {
final Matcher matcher = EQN.matcher(eq);
if (!matcher.matches()) {
throw new IllegalArgumentException("Not a valid pattern " + eq);
}
final int a = Integer.parseInt(matcher.group(1));
final int b = Integer.parseInt(matcher.group(2));
final int c = Integer.parseInt(matcher.group(3));
return new QuadraticEq(a, b, c);
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("QuadraticEq{");
sb.append("a=").append(a);
sb.append(", b=").append(b);
sb.append(", c=").append(c);
sb.append('}');
return sb.toString();
}
}
Note the \\, this is required by Java.
A quick test:
System.out.println(QuadraticEq.parseString("4x2-4x-42=0"));
Output:
QuadraticEq{a=4, b=-4, c=-42}
If you are only using quadratics:
int xsqrd = equation.indexOf("x2");
int x = equation.indexOf("x", xsqrd);
int equ = equation.indexOf("=");
String a = equation.subString(0,xsqrd);
String b = equation.subString(xsqrd+1,x);
String c = equation.subString(x,equ);
I may have messed up the substrings but you get the general idea.
The first note: if you use symbol as delimiter in regexp, you will lose it in slpitted elements. I suggest you use the folllowing regexp:
"x2|x|="
Then, you can got only numbers.
The full fragment of code is:
public class Main {
private static final char[] varNames = {'a', 'b', 'c'};
public static void main(String[] args) {
String equation = "4x2-4x-42=0";
String[] parts = equation.split("x2|x|=");
// you will get 4 elements, but the last element is always 0
for(int i=0; i<parts.length - 1; i++){
System.out.println(varNames[i] + " = " + Integer.parseInt(parts[i]));
}
}
}
But in this case you will have the '+' symbols in output. To avoid it, you may use Integer.parseInt(parts[i]) instead of parts[i].
for ( int i = 0 ; i < str.length ; ++i ){
if(asciiOf(str.charAt(i)) == asciiOfIntegerValue ){
addCharInArrayList(str.charAt(i));
}else{
addInFuncList();
addCharInArrayList("_");
}
// join numbers which are not separated by _ and apply BODMAS rule and solve it
// fyi : apologies - very inefficient pseudocode, wrote in a haste
You can use a regex as follows:
final String regex = "([+-]?\\d+)x2([+-]\\d+)x([+-]\\d+)=0";
Pattern pattern = Pattern.compile(regex);
final String equation = "4x2-4x-42=0";
Matcher matcher = pattern.matcher(equation);
if (matcher.matches()) {
int a = Integer.parseInt(matcher.group(1));
int b = Integer.parseInt(matcher.group(2));
int c = Integer.parseInt(matcher.group(3));
System.out.println("a=" + a + " b=" + b + " c=" + c);
}
Output:
a=4 b=-4 c=-42

how to split a string by position in Java

I did not find anywhere an answer.. If i have: String s = "How are you"?
How can i split this into two strings, so first string containing from 0..s.length()/2 and the 2nd string from s.length()/2+1..s.length()?
Thanks!
This should do:
String s = "How are you?";
String first = s.substring(0, s.length() / 2); // gives "How ar"
String second = s.substring(s.length() / 2); // gives "e you?"
String.substring(int i) with one argument returns the substring beginning at position i
String.substring(int i, int j) with two arguments returns the substring beginning at i and ending at j-1.
(Note that if the length of the string is odd, second will have one more character than first due to the rounding in the integer division.)
String s0 = "How are you?";
String s1 = s0.subString(0, s0.length() / 2);
String s2 = s0.subString(s0.length() / 2);
So long as s0 is not null.
EDIT
This will work for odd length strings as you are not adding 1 to either index. Surprisingly it even works on a zero length string "".
You can use 'substring(start, end)', but of course check if string isn't null before:
String first = s.substring(0, s.length() / 2);
String second = s.substring(s.length() / 2);
http://www.roseindia.net/java/beginners/SubstringExample.shtml
And are you expecting string with odd length ? in this case you must add logic to handle this case correctly.
Here's a method that splits a string into n items by length. (If the string length can not exactly be divided by n, the last item will be shorter.)
public static String[] splitInEqualParts(final String s, final int n){
if(s == null){
return null;
}
final int strlen = s.length();
if(strlen < n){
// this could be handled differently
throw new IllegalArgumentException("String too short");
}
final String[] arr = new String[n];
final int tokensize = strlen / n + (strlen % n == 0 ? 0 : 1);
for(int i = 0; i < n; i++){
arr[i] =
s.substring(i * tokensize,
Math.min((i + 1) * tokensize, strlen));
}
return arr;
}
Test code:
/**
* Didn't use Arrays.toString() because I wanted to have quotes.
*/
private static void printArray(final String[] arr){
System.out.print("[");
boolean first = true;
for(final String item : arr){
if(first) first = false;
else System.out.print(", ");
System.out.print("'" + item + "'");
}
System.out.println("]");
}
public static void main(final String[] args){
printArray(splitInEqualParts("Hound dog", 2));
printArray(splitInEqualParts("Love me tender", 3));
printArray(splitInEqualParts("Jailhouse Rock", 4));
}
Output:
['Hound', ' dog']
['Love ', 'me te', 'nder']
['Jail', 'hous', 'e Ro', 'ck']
Use String.substring(int), and String.substring(int, int) method.
int cutPos = s.length()/2;
String s1 = s.substring(0, cutPos);
String s2 = s.substring(cutPos, s.length()); //which is essentially the same as
//String s2 = s.substring(cutPos);
I did not find anywhere an answer.
The first place you should always look is at the javadocs for the class in question: in this case java.lang.String. The javadocs
can be browsed online on the Oracle website (e.g. at http://download.oracle.com/javase/6/docs/api/),
are included in any Sun/Oracle Java SDK distribution,
are probably viewable in your Java IDE, and
and be found using a Google search.
public int solution(final String S, final int K) {
int splitCount = -1;
final int count = (int) Stream.of(S.split(" ")).filter(v -> v.length() > K).count();
if (count > 0) {
return splitCount;
}
final List<String> words = Stream.of(S.split(" ")).collect(Collectors.toList());
final List<String> subStrings = new ArrayList<>();
int counter = 0;
for (final String word : words) {
final StringJoiner sj = new StringJoiner(" ");
if (subStrings.size() > 0) {
final String oldString = subStrings.get(counter);
if (oldString.length() + word.length() <= K - 1) {
subStrings.set(counter, sj.add(oldString).add(word).toString());
} else {
counter++;
subStrings.add(counter, sj.add(word).toString());
}
} else {
subStrings.add(sj.add(word).toString());
}
}
subStrings.forEach(
v -> {
System.out.printf("[%s] and length %d\n", v, v.length());
}
);
splitCount = subStrings.size();
return splitCount;
}
public static void main(final String[] args) {
final MessageSolution messageSolution = new MessageSolution();
final String message = "SMSas5 ABC DECF HIJK1566 SMS POP SUV XMXS MSMS";
final int maxSize = 11;
System.out.println(messageSolution.solution(message, maxSize));
}

Categories