Regular Expressions - match a string containing "+" and "-" - java

I have a string, say 1+++-3--+++++2 that includes + and - sign.
What I want to do is to represent the + and - part with + or - sign.
If there are an odd number of - sign in the string, I will replace it with -, and + if that is an even number. How can I do that using regex?
For example, I have a math expression, say 1+-+-2-+--+3. It will be replaced by 1+2-3

You can create an array of the operators and use a for loop to count all occurrences of one character. For example:
String expression = "1+++-3--+++++2";
String[] str = expression.split("[0-9]+");
for(op : str) {
int count = 0;
for(int i =0; i < str.length(); i++)
if(op.charAt(i) == '-')
count++;
if(count % 2 == 0) {
op = "-";
}
else {
op = "+";
}
}
After assigning the modified one-character operators in str[], it should be relatively simple to write the new expression.

based on the assumption that the format will be from that calculator example.
//assumed format for input: <any number><any number of `-` and/or `+`><any number>
// 1++---+22+--1 will be 1-22+1
String input = "1++---+22+--1";
for (String s : input.split("[^-+]+");) {
s = s.trim();
if (!"".equals(s)) {
String newStr = s.matches("[+]*-([+]*-[+]*-)*[+]*") ? "-" : "+";
input = input.replace(s, newStr);
}
}
System.out.println(input);

Related

int and char concatenation in java [duplicate]

This question already has answers here:
char + int gives unexpected result
(3 answers)
Closed 2 years ago.
This program receives a word as an input, and if the length of the word is greater than 10, then it should print the first letter of the word, then the number of characters in between the first and last letter, followed by the last letter. Such an input like "introduction" should output i10n. However, when I try concatenating each of them, something goes wrong, so it just outputs 224, which I have no clue why. Why does this happen, and how can I fix this issue? Any help would be appreciated.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++){
String word = sc.next();
if (word.length() > 10){
int lettersInBetween = (word.length() - 2);
char firstChar = word.charAt(0);
char lastChar = word.charAt(word.length() - 1);
System.out.println(firstChar + lettersInBetween + lastChar);
}
else {
System.out.println(word);
}
}
}
}
Try this:
System.out.println(firstChar + Integer.toString(lettersInBetween) + lastChar);
About the output of the number 224, this explains it very well:
https://en.wikipedia.org/wiki/ASCII
"For example, lowercase i would be represented in the ASCII encoding by binary 1101001 = hexadecimal 69 (i is the ninth letter) = decimal 105."
just replace line :
System.out.println(firstChar + lettersInBetween + lastChar);
with below line :
System.out.println(""+firstChar + lettersInBetween + lastChar);
The easiest way of joining multiple String and numeric values in Java. Just remember that, when you have two or more primitive type values e.g. char, short, or int, at the beginning of your string concatenation, you need to explicitly convert the first of them to a String.
String.valueOf(int i) method takes an integer value as an argument and returns a string representing the int argument.
Integer.toString(int i) method works same as String.valueOf(int i) method. It belongs to the Integer class and converts the specified integer value to String. for e.g. if the passed value is 101 then the returned string value would be “101”.
You can you both of these methods to convert the integer to String.
int lettersInBetween = (word.length() - 2);
char firstChar = word.charAt(0);
char lastChar = word.charAt(word.length() - 1);
String number = String.valueOf(lettersInBetween);
System.out.println(firstChar + number + lastChar);
or
int lettersInBetween = (word.length() - 2);
char firstChar = word.charAt(0);
char lastChar = word.charAt(word.length() - 1);
String number = Integer.toString(lettersInBetween);
System.out.println(firstChar + number + lastChar);

Check if charAt are the same (case sensitive)

Im have to write a method to check if a word is a palindrome. There is probably a easier way then I have it but this is just based off what I have learned so far. My method works except if there is a capital letters compared to a lowercase.
Edit: wasn't very clear. My method returns that a capital and lower case letter are the same. But I would like it to say they are different
public static void printPalindrome(Scanner kb) {
System.out.print("Type one or more words: ");
String s = kb.nextLine();
int count = 0;
for(int i = 0; i < s.length();i++) {
char a = s.charAt(i);
char b = s.charAt(s.length()-(i+1));
if (a==b) {
count ++;
} else {
count = count;
}
}
if (count == s.length()) {
System.out.print(s + " is a palindrome!");
} else {
System.out.print(s + " is not a palindrome.");
}
}
I'd recommend a slightly different approach, I'd reverse the string using StringBuilder#reverse and then compare the two strings using String#equalsIgnoreCase
String s = kb.nextLine();
StringBuilder sb = new StringBuilder(s).reverse();
if (s.equalsIgnoreCase(sb.toString())) {
...
} else {
...
}
You can solve your problem by converting the input String to upper case :
String s = kb.nextLine().toUpperCase();
Or if you wish to preserve the case of the original String, create a new String and test if it's a palindrome.
String s = kb.nextLine();
String u = s.toUpperCase();
int count = 0;
for(int i = 0; i < u.length();i++) {
char a = u.charAt(i);
char b = u.charAt(u.length()-(i+1));
if (a==b) {
count ++;
} else {
count = count;
}
}
i think you can do it with its ascii values
look this picture
then you shoul convert your char to ascii
char character = 'a';
int ascii = (int) character;
then compare the integers

Split javaString into substring of characters and numeric value

My Requirement is like , split the given string into sub strings of charter and numeric values.
And the input value will always begin charter only.
Input : String strValue = "ABCD12345";
Out put:
A1 = ABCD
A2 = 12345
You need to use lookaround assertions.
String s = "ABCD12345";
String parts[] = s.split("(?<=[A-Za-z])(?=\\d)");
System.out.println(Arrays.toString(parts));
(?<=[A-Za-z])(?=\\d) regex would match the boundary which exists between alphabets and digits. Splitting according to the matched boundary will ive you the desired output.
Output:
[ABCD, 12345]
There's probably some mistakes and probably not the most efficient here but here's a vauge shot. Feedback welcome of course.
var char;
var = num;
str = "somestring23498";
for(i=1:1=str.length - 1;i++){
if ((typeof str[i] + 1) == "string"){
char = char + str[i];
} else if((typeof str[i] + 1) == "integer"){
num = num + str[i];
}
}
You can alternatively create a char buffer with space or a delimeter between char boundary.
String str = "ABCD1234cda209ad";
char[] chars = new char[2*str.length()];
int i=0;
boolean isPrevcharANum = false;
for(char c:str.toCharArray()){
if(Character.isDigit(c)){
if(!isPrevcharANum){
chars[++i] = ' ';
}
isPrevcharANum = true;
}else{
if(isPrevcharANum){
chars[++i] = ' ';
isPrevcharANum = false;
}
}
chars[++i] = c;
}
System.out.println("Output : "+new String(chars));
Output : ABCD 1234 cda 209 ad
again with regex but shorter
String parts[] = s.split("(?<=\\D)(?=\\d)"); // [ABCD, 12345]
Internally, split() uses a Pattern to find the place where to split. The first part in braces is a positive lookbehind.
\D is the oposite to \d and means each character but a digit.
The second part in braces is a positive lookahead \d which means here must be a digit.
So a split is made when to the left of the position is any character but a digit and at the same time there is a digit in this position.

Splitting an input currency into a string and an int

In a program where currency is input in the form £2 or 10p, for example, is there a method to split this into two variables in the form
currencyType = £
currencyValue = 2
or
currencyType = p
currencyValue = 10
where currencyType is a string and currencyValue is an int?
An idea for a solution without regular expressions, although I'd prefer one of those:
String entry = "€2.73";
StringBuilder currency = new StringBuilder();
StringBuilder value = new StringBuilder();
for (char c : entry.toCharArray()) {
if (Character.isDigit(c) || c == '.' || c == ',') {
value.append(c);
} else {
currency.append(c);
}
}
System.out.println("Value = " + value + " Currency = " + currency);
Use patten and matcher classes like below. \d+ matches one or more digits where \D+ matches one or more non-digit characters.
String s1 = "£2";
Matcher m = Pattern.compile("(\\D+)|(\\d+)").matcher(s1);
while(m.find())
{
if (m.group(1) != null)
System.out.println("Currency Type: " + m.group(1));
if (m.group(2) != null)
System.out.println("Currency Value: " + m.group(2));
}
Output:
Currency Type: £
Currency Value: 2
OR
Use this regex, if you want to deal also with the decimal value.
Pattern.compile("(\\D+)|(\\d+(?:\\.\\d+)?)");
DEMO
You can use this regular expression to get your result: "(.*?)([\\d,]*)(.*?)"
This will split the input into three groups:
1) Leading currency token
2) Value token (can contain a ',', in the string version you can replaceAll ',' with '' and then convert to integer)
3) Trailing currency token
By looking at the groups from the regex, you can figure out if the leading or trailing currency is present and then get the value from the second group. You can write the code yourself by looking up usage for java regex.
You can input your value as a string, split it normally with the split function and assign each value to its own string. Then convert the string to an integer.
int currencyValue = Integer.parseInt(array[0]);
String currencyType = array[1];
array[] is the array that you split the string into.
String input = user_input.nextLine();
char[] array = input.toCharArray();
for(int i = 0; i < input.length(); i++) {
if (Character.isLetter(array[i])){
//use .split based on the output of the if statement
}
}

Get the last word in a string using a for loop?

I have to find the last word in a string and can't understand why my code isn't working. This is what I have:
int i, length;
String j, lastWord;
String word = "We the people of the United States in order to form a more perfect union";
length = word.length();
for (i = length - 1; i > 0; i--)
{
j = word.substring(i, i + 1);
if (j.equals(" ") == true);
{
lastWord = word.substring(i);
System.out.println("Last word: " + lastWord);
i = -1; //to stop the loop
}
}
However, when I run it, it prints the last letter. I know I could use
String lastWord = word.substring(word.lastIndexOf(" ") + 1)
But I'm pretty sure my teacher doesn't want me to do it this way. Any help?
You need to remove the ; after the if to make it work:
if (j.equals(" ")) // <== No semicolon, and no == true
{
lastWord = word.substring(i);
System.out.println("Last word: " + lastWord);
i = -1; //to stop the loop
}
You do not need == true for booleans inside control statements, either.
Finally, making single-character substrings is more expensive than using single characters. Consider using charAt(i) instead:
if (word.charAt(i) == ' ') // Single quotes mean one character
{
lastWord = word.substring(i+1);
System.out.println("Last word: " + lastWord);
break; // there is a better way to stop the loop
}
You've terminated the if statement. It should be,
if(j.equals(" "))
{
...
}
Just take that ; from if (j.equals(" ") == true); out.
Your code remade cleaner:
String word = "We the people of the United States in order to form a more perfect union";
for (int i = word.length() - 1; i > 0; i--)
if (word.charAt(i - 1) == ' ') {
System.out.println("Last word: " + word.substring(i));
break; // To stop the loop
}
Minimum iterations.
Convert the string to char array and look for space from the end of array. Don't forget to remove white spaces from the end using trim() as they could be counted as separate words.
s = s.trim();
char[] c = s.toCharArray();
for(int i=0; i<c.length; i++)
{
if(c[c.length-1-i]==' ')
{
return s.substring(c.length-1-i);
}
}
return s;
This also covers the null string case.
Another alternative using split.
s = s.trim();
String[] strs = new s.split(' ');
return str[str.length-1];
The semicolon after your "if" statement means "do nothing." Also, the "== true" is redundant. Lastly, you don't want to include the space you just found. Try this:
for (i = length - 1; i > 0; i--)
{
j = word.substring(i, i + 1);
if (j.equals(" "))
{
lastWord = word.substring(i + 1);
System.out.println("Last word: " + lastWord);
i = -1; //to stop the loop
}
}
There's a method for strings to split up at http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split%28java.lang.String%29
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
A good, fast and easier way would be:
word = word.split(" ")[word.length-1];
split() returns an array of substrings based on " ". Since an array starts with 0, its last element is the length of the array - 1.

Categories