java controle upper and lowercase in 2 String - java

I want to check if every character in a string is the inverse of the other character in the second. By inverse I mean uppercase and lowercase.
For example these strings:
Ahh7h
aHH7H
The result will be true
I wrote this code but the result is always false. Why?
public boolean checkString(String serverString, String clientString) {
if (serverString.length() != clientString.length())
return false;
else
for (int i = 0; i < clientString.length(); i++) {
if ((clientString.charAt(i) >= '0' && clientString.charAt(i) <= '9')
&& (clientString.charAt(i) != serverString.charAt(i)))
return false;
else if (clientString.charAt(i) >= 'A'
&& clientString.charAt(i) <= 'Z') {
if ((int) clientString.charAt(i) != ((int) serverString
.charAt(i) + 32))
return false;
} else if (clientString.charAt(i) >= 'a'
&& clientString.charAt(i) <= 'z') {
if ((int) clientString.charAt(i) != ((int) serverString
.charAt(i) - 32))
return false;
}
}
return true;
}

You could "invert" one string using: How can I invert the case of a String in Java? and then use Strings .equals method to compare them.
Method from How can I invert the case of a String in Java? included for completeness:
public static String reverseCase(String text)
{
char[] chars = text.toCharArray();
for (int i = 0; i < chars.length; i++)
{
char c = chars[i];
if (Character.isUpperCase(c))
{
chars[i] = Character.toLowerCase(c);
}
else if (Character.isLowerCase(c))
{
chars[i] = Character.toUpperCase(c);
}
}
return new String(chars);
}

You've switched the + 32 and the - 32.
By the way, it's a lot easier to use methods like:
Character.isDigit
Character.isLowerCase
Character.isUpperCase
Character.toLowerCase
Character.toUpperCase

Related

Checking if a string is composed of 3 capital letters and 4 numbers (in JAVA)

I need to check if a string is composed by 3 capital letters and 4 digits.
For example: ABC1234
OBS: Without using regular expressions?
This is what I have tried so far. Thanks!
public static void main(String[] args) {
String input = "ABC1234";
String firstThreeChars = ""; //substring containing first three characters
String lastFourChars = ""; //substring containing last four characters
if (input.length() > 4) {
firstThreeChars = input.substring(0, 3);
}
if (input.length() > 4) {
lastFourChars = input.substring(input.length() - 4);
}
System.out.println(firstThreeChars);
System.out.println(lastFourChars);
}
I'm guessing that the letters and numbers are in random places in the string.
Just use two counters and count.
if (input.length != 7) {
System.out.println("No");
return;
}
int letterCount = 0, digitCount = 0;
for (int i = 0; i < 7; ++i) {
char c = input.charAt(i);
if (c >= 'A' && c <= 'Z') {
++letterCount;
} else if (c >= '0' && c <= '9') {
++digitCount;
} else {
System.out.println("No");
return;
}
}
if (letterCount == 3 && digitCount == 4) {
System.out.println("Yes");
} else {
System.out.println("No");
}

How to add 0 in front of every single digit string?

How can I add 0 in front of every single digit number? I mean 1 to 01 etc.
I have tried to add ifs like
if(c >='A' && c<= 'I')
str = "0"+str;
but it just adds 0 in front of everything like abcd converts to 00001234 not 01020304.
This is my code.
String A[] = new String[size];
for (int i = 0; i < size; i++) {
A[i] = jList1.getModel().getElementAt(i);
String[] Text = A[i].split("");
String s = jList1.getModel().getElementAt(i);
String str = ("");
for (int z = 0; z < Text.length; z++) {
for (int y = 0; y < Text[z].length(); y = y + 1) {
char c = s.charAt(z);
if (c >= 'A' && c <= 'Z') {
str += c - 'A' + 1;
} else if (c >= 'a' && c <= 'z') {
str += c - 'a' + 1;
} else {
str += c;
}
}
str = str + "";
}
}
This Worked for me
public String addZero(int number)
{
return number<=9?"0"+number:String.valueOf(number);
}``
One way to do this would be to use a StringJoiner with Java 8:
String s = "abcdABCD";
s = s.chars()
.mapToObj(i -> Integer.toString((i >= 'a' && i <= 'z' ? i - 'a' : i - 'A') + 1))
.collect(Collectors.joining("0", "0", "")));
System.out.println(s);
>> 0102030401020304
String str = "abcd-zzz-AAA";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char ch = str.toLowerCase().charAt(i);
if (ch >= 'a' && ch <= 'z') {
sb.append('0');
sb.append(ch - 'a' + 1);
} else {
sb.append(ch);
}
}
Result: abcd-zzz-AAA -> 01020304-026026026-010101
Final fix :-)
use String#chars to get a stream of its characters, then for each one do the manipulation you want.
public class Example {
public static void main(String[] args) {
String s = "aBcd1xYz";
s.chars().forEach(c -> {
if (c >= 'a' && c <= 'z')
System.out.print("0" + (c - 'a' + 1));
else if (c >= 'A' && c <= 'Z')
System.out.print("0" + (c - 'A' + 1));
else
System.out.print(c);
});
}
}
Ouput:
0102030449024025026
You can add zero in front of single digit number using String.format.
System.out.println(String.format("%02d",1));
System.out.println(String.format("%02d",999));
The first line will print 01, second line prints 999 no zero padding on the left.
Padding zero with length of 2 and d represents integer.
I hope this helps.

I am trying to convert string into integer, but I cannot print the result out

I am trying to convert string into integers but when I try to print the result I cannnot get the right output.
package com.company;
public class Main {
public static void main(String[] args){
String str ="-123456";
int i = atoi(str);
System.out.println(i);
}
public static int atoi(String str){
if (str == null || str.length() < 1)
return 0;
str = str.trim();
char flag = '+';
int i = 0;
if (str.charAt(0) == '-'){
flag = '-';
i++;
} else if (str.charAt(0) == '+'){
i++;
}
double result = 0;
while (str.length() > 1 && str.charAt(i) >= '0' && str.charAt(i) <= '9'){
result = result * 10 + (str.charAt(i)-'0');
i++;
}
if (flag == '-'){
result = -result;
}
if (result > Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
if (result < Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}
return (int) result;
}
}
This is the result after I run the code
Change to this: Note i < str.length() instead of str.length() > 1
Explanation: Your error was "index out of range" meaning you're trying to access a character that isn't in the range of the length of the straight and ins this case str.charAt(7), which doesn't exist, so you have to limit i to being less than length of the string.
while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9'){
result = result * 10 + (str.charAt(i)-'0');
i++;
}

How do I compare strings representation of integers?

I was wondering how I could use an if statement as if they were integers for strings?
/**
*
* #param token
* #return true if parameter is the String representation of an integer
* between 0 and 255 (including 0 and 255), false otherwise.
* Strings "0", "1", "2" .... "254", "255" are valid.
* Padded Strings (such as "00000000153") are also valid
*/
public static boolean isValidElement(String token) {
if (token=> 0 || token <=255)
return true;
return false;
}
This is what I currently have in mind at the moment but obviously it won't work for strings.
You could use Integer.parseInt(), but it allows a leading +, and that's not allowed according to your javadoc.
You can manually test for leading +, then use Integer.parseInt() like this:
public static boolean isValidElement(String token) {
if (token == null || token.isEmpty() || token.charAt(0) == '+')
return false;
try {
int num = Integer.parseInt(token);
return (num >= 0 && num <= 255);
} catch (#SuppressWarnings("unused") NumberFormatException e) {
return false;
}
}
For a high-performance solution that don't rely on parseInt() and exception handling, you can use this much longer implementation:
public static boolean isValidElement(String token) {
if (token == null || token.isEmpty())
return false;
// skip leading zeroes
int i = 0;
while (i < token.length() && token.charAt(i) == '0')
i++;
// validate remaining
char ch;
switch (token.length() - i) {
case 0:
return true; // Allow "0"
case 1:
ch = token.charAt(i);
return (ch >= '1' && ch <= '9'); // Allow "1" to "9"
case 2:
ch = token.charAt(i);
if (ch >= '1' && ch <= '9') {
ch = token.charAt(i + 1);
return (ch >= '0' && ch <= '9'); // Allow "10" to "99"
}
return false;
case 3:
ch = token.charAt(i);
if (ch == '1') {
ch = token.charAt(i + 1);
if (ch >= '0' && ch <= '9') {
ch = token.charAt(i + 2);
return (ch >= '0' && ch <= '9'); // Allow "100" to "199"
}
} else if (ch == '2') {
ch = token.charAt(i + 1);
if (ch >= '0' && ch <= '4') {
ch = token.charAt(i + 2);
return (ch >= '0' && ch <= '9'); // Allow "200" to "249"
} else if (ch == '5') {
ch = token.charAt(i + 2);
return (ch >= '0' && ch <= '5'); // Allow "250" to "255"
}
}
return false;
default:
return false;
}
}
Try this:
if (Integer.parseInt(token) >= 0 || Integer.parseInt(token) <= 255) {
System.out.println(true);
}
This will cast the String token using the Integer wrapper class.
Use Integer.parseInt(yourString) for parsing an integer from String. You could try this:
public static boolean isValidElement(String token) {
try {
Integer n = Integer.parseInt(token);
return (n >= 0 && n <= 255);
} catch (NumberFormatException nfe) {
return false;
}
}

Codingbat sameStarChar exercise

I'm having trouble with this codingbat exercise:
Returns true if for every * (star) in the string, if there are chars both immediately before and after the star, they are the same.
sameStarChar("xyyzz") // true
sameStarChar("xyzzz") // false
sameStarChar("xaaz") // true
The right answer is:
public boolean sameStarChar(String str) {
for (int i = 1; i < str.length() - 1; i++) {
if (str.charAt(i) == '*' && str.charAt(i - 1) != str.charAt(i + 1)) {
return false;
}
}
return true;
}
What I wrote is:
public boolean sameStarChar(String str) {
for (int i = 1; i < str.length() - 1; i++) {
if (str.substring(i, i + 1) == "*" && str.substring(i - 1, i) != str.substring(i + 1, i + 2)) {
return false;
}
}
return true;
}
I'm having trouble understanding the substring and charAt methods.
Instructions:
Returns true if for every '*' (star) in the string, if there are chars both immediately before and after the star, they are the same.
sameStarChar("xy*yzz") → true
sameStarChar("xy*zzz") → false
sameStarChar("*xa*az") → true
Pseudocode:
Loop over every character from 1 to length-1. If the character is an asterisk and the character before it is different from the one after, return false. Otherwise if when you reach the end, return true.
Code:
public boolean sameStarChar(String str){
int len = str.length();
for(int x = 1; x < len-1; x++){
if (str.charAt(x) == '*' && str.charAt(x-1) != str.charAt(x+1)){
return false;
}
}
return true;
}
Comments:
It's a linear time O(n) operation.
str.charAt() is easier to read and understand in this case.
Also, your substring solution should be more like
if (str.substring(i, i + 1).equals("*") &&
!str.substring(i - 1, i).equals(str.substring(i + 1, i + 2))){
//etc.
}
Substring returns a string, and to compare the literal sting value you have to use the .equals() method.
Instead, I count the number of '*' and number of pairs that are matched and check if they both are equal and return true.
public boolean sameStarChar(String str) {
int count=0, noOfPairs=0;
for(int i=1; i<str.length()-1;i++){
if(str.charAt(i)=='*') count++;
if(str.charAt(i)=='*' && str.charAt(i+1)==str.charAt(i-1)) noOfPairs++;
}
if(count==noOfPairs) return true;
return false;
}
Another solution to look at...
public boolean sameStarChar(String str) {
if(str.length()==0) return true;
if(str.length()==1 && str.contains("*")) return true;
if(!str.contains("*")) return true;
int i = 0;
boolean result = false;
while(i<str.length()-1){
if(i!=0 && str.charAt(i) == '*' && str.charAt(i-1) == str.charAt(i+1)){
result = true;
}else if(i!=0 && str.charAt(i) == '*' && str.charAt(i-1) != str.charAt(i+1)){
result = false;
}else if(str.charAt(i) == '*'){
result = true;
}
i++;
}
return result;
}
A version which does not iterate over each individual character in the string by using indexOf(int ch, int fromIndex)
public boolean sameStarChar(String str) {
int i=0;
int l=str.length();
for(i=str.indexOf("*",i);i!=-1;i=str.indexOf("*",i+1))
{
if(i==0 || i==l-1) //saves the program from accessing an out of bounds Index
continue;
else
{
if(str.charAt(i-1)!=str.charAt(i+1));
return false;
}
}
return true;
}

Categories

Resources