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.
Related
The user must do the question above or the question keeps repeating so I need a while loop. I need to do this using a subroutine too. My code below isn't working.
public static boolean isAlpha(String name) {
char[] chars = name.toCharArray();
for (char c : chars) {
if (!Character.isLetter(c)) {
return false;
}
else {
for (int i = 0; i < name.length(); i++) {
if (name.charAt(i) >= 'a') {
return false;
}
else {
return false;
}
}
}
}
return false;
}
This is the second part:
System. out.print ("Please enter a string that contains at least one lowercase a. ");
String name = input.next ();
if (isAlpha(name)) {
System.out.println("That is a valid string onto stage 2.");
}
else {
System.out.println("That is an invalid string. Try again.");
}
You're passing a String to the isAlpha method, which iterates over the String and checks each letter to be 'a' or not. You're returning false for every char that isn't 'a', and returning false if you iterate through the entire String.
An easier way to handle this would be to return true upon finding the first 'a', or returning false after iterating over the entire String. It will make scaling easier as well if you reduce the number of return statements in a single method.
Here are three different ways to check whether a string contains at least one lowercase a. The first way uses a for loop as you have tried to do in the code in your question.
The second way uses regular expressions and the last way uses streams.
The code also contains a main method which contains a while loop as requested in your question.
do the question above or the question keeps repeating
import java.util.Scanner;
public class Solution {
public static boolean isAlpha(String name) {
/* Using a loop. */
char[] chars = name.toCharArray();
for (char ch : chars) {
if (ch == 'a') {
return true;
}
}
return false;
/* Using regular expression. */
// return name.matches("^.*a.*$");
/* Using stream API. */
// return name.chars()
// .filter(c -> c == 'a')
// .findFirst()
// .isPresent();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter a string that contains at least one lowercase 'a': ");
String str = input.nextLine();
while (!isAlpha(str)) {
System.out.println("That is an invalid string. Try again.");
str = input.nextLine();
}
System.out.println("That is a valid string. On to stage 2.");
}
}
Here is a sample run:
Please enter a string that contains at least one lowercase 'a': 1 is the lonliest number.
That is an invalid string. Try again.
2 can be as bad as 1
That is a valid string. On to stage 2.
A couple of mistakes were made. Firstly, your method only returns false, there is no way in which it could be true. Secondly, your code here loops through the entire array for every single character.
public static Boolean isAlpha(String name) {
char[] chars = name.toCharArray();
for (char c : chars) {
if (!Character.isLetter(c)) {
return false;
}
else {
for (int i = 0; i < name.length(); i++) {
if (name.charAt(i) >= 'a') {
return false;
}
else {
return false;
}
}
}
}
return false;
}
Try this instead.
public static Boolean isAlpha(String name) {
char[] chars = name.toCharArray();
for(char c : chars) {
if(c=='a') {
return true;
}
}
return false;
}
My code doesnt convert ex. dog_cat_dog into dogCatDog. The out put of my code is dogCat_dog. Trying to make a loop that doesn't stop at the first "_":
public String underscoreToCamel(String textToConvert) {
int index_= textToConvert.indexOf("_",0);
String camelCase="";
String upperCase = "";
String lowerCase="";
for (int i=0; i < textToConvert.length(); i++){
if(i==index_){
upperCase= (textToConvert.charAt(index_+1)+upperCase).toUpperCase();
upperCase= upperCase+ textToConvert.substring(index_+2);
}
else{
lowerCase=textToConvert.substring(0,index_);
}
camelCase=lowerCase+upperCase;
}
return camelCase;
}
I would do the following: make the method static, it does not use any class state. Then instantiate a StringBuilder with the passed in value, because that is mutable. Then iterate the StringBuilder. If the current character is underscore, delete the current character, then replace the now current character with its upper case equivalent. Like,
public static String underscoreToCamel(String s) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == '_') {
sb.deleteCharAt(i);
char ch = Character.toUpperCase(sb.charAt(i));
sb.setCharAt(i, ch);
}
}
return sb.toString();
}
I tested like
public static void main(String[] args) {
System.out.println(underscoreToCamel("dog_cat_dog"));
}
Which outputs (as requested)
dogCatDog
You can split on '_' then rebuild.
public static String underscoreToCamel(String textToConvert) {
String [] words = textToConvert.split("_");
StringBuilder sb = new StringBuilder(words[0]);
for (int i = 1; i < words.length; i++) {
sb.append(Character.toUpperCase(words[i].charAt(0)));
sb.append(words[i].substring(1));
}
return sb.toString();
}
I think an easy way to solve this is to first consider the base cases, then tackle the other cases
public static String underscoreToCamel(String textToConvert){
//Initialize the return value
String toReturn = "";
if (textToConvert == null){
//Base Case 1: null value, so just return an empty string
return "";
} else if (textToConvert.indexOf("_") == -1) {
//Base Case 2: string without underscore, so just return that string
return textToConvert;
} else {
//Primary Case:
//Find index of underscore
int underscore = textToConvert.indexOf("_");
//Append everything before the underscore to the return string
toReturn += textToConvert.substring(0, underscore);
//Append the uppercase of the first letter after the underscore
toReturn += textToConvert.substring(underscore+1, underscore+2).toUpperCase();
//Append the rest of the textToConvert, passing it recursively to this function
toReturn += underscoreToCamel(textToConvert.substring(underscore+2));
}
//Final return value
return toReturn;
}
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
Here is the problem statement: Write a function that compares 2 strings to return true or false depending on if both strings contain the same letters. Order doesn't matter.
I do not know how to properly compare the character arrays in my nested for loop. I wish I could be more specific with what my issue is, but I'm a really new learner and can't see why this isn't working. I do believe it's not doing what I would like in the nested for loops. Thanks in advance!
import java.util.Scanner;
public class PracticeProblems {
public static boolean stringCompare(String word1, String word2) {
char[] word1b = new char[word1.length()];
char[] word2b = new char[word2.length()];
boolean compareBool = false;
for(int i = 0; i < word1.length(); i++) {
word1b[i] = word1.charAt(i);
word2b[i] = word2.charAt(i);
}
for(int i = 0; i < word1.length(); i++) {
for(int j = 0; j < word2.length(); j++) {
if(word1b[i] == word2b[j]) {
compareBool = true;
break;
} else {
compareBool = false;
break;
}
}
}
return compareBool;
}
public static void main(String []args) {
Scanner scan = new Scanner(System.in);
System.out.println("Word 1?");
String word1 = scan.nextLine();
System.out.println("Word 2?");
String word2 = scan.nextLine();
if(PracticeProblems.stringCompare(word1, word2) == true) {
System.out.println("Same Letters!");
} else {
System.out.println("Different Letters...");
}
}
The code below will do the job. This is essentially an expansion of Frank's comment above. We convert the two strings to two sets and then compare.
import java.util.*;
public class SameChars {
// Logic to convert the string to a set
public static Set<Character> stringToCharSet(String str) {
Set<Character> charSet = new HashSet<Character>();
char arrayChar[] = str.toCharArray();
for (char aChar : arrayChar) {
charSet.add(aChar);
}
return charSet;
}
// Compares the two sets
public static boolean hasSameChars(String str1, String str2) {
return stringToCharSet(str1).equals(stringToCharSet(str2));
}
public static void main(String args[]){
// Should return true
System.out.println(hasSameChars("hello", "olleh"));
// Should returns false
System.out.println(hasSameChars("hellox", "olleh"));
}
}
I sorted arrays before comparing.
//import statement for Arrays class
import java.util.Arrays;
import java.util.Scanner;
public class PracticeProblems {
public static boolean stringCompare(String word1, String word2) {
char[] word1b = new char[word1.length()];
char[] word2b = new char[word2.length()];
boolean compareBool = true;
for(int i = 0; i < word1.length(); i++) {
word1b[i] = word1.charAt(i);
}
//sort the new char array
Arrays.sort(word1b);
// added a second loop to for the second world
for(int i = 0; i < word2.length(); i++) {
word2b[i] = word2.charAt(i);
}
Arrays.sort(word2b);
for(int i = 0; i < word1.length(); i++) {
//removed second for loop.
// for(int j = 0; j < word2.length(); j++) {
// if the two strings have different length, then they are different
if((word1.length()!=word2.length())){
compareBool = false;
break;
}
//changed to not equal
if( (word1b[i] != word2b[i]) ) {
compareBool = false;
break;
}
//removed else statment
// else {
// compareBool = false;
// break;
//
// }
}
return compareBool;
}
public static void main(String []args) {
Scanner scan = new Scanner(System.in);
System.out.println("Word 1?");
String word1 = scan.nextLine();
System.out.println("Word 2?");
String word2 = scan.nextLine();
if(PracticeProblems.stringCompare(word1, word2) == true) {
System.out.println("Same Letters!");
} else {
System.out.println("Different Letters...");
}
//resource leak. use close() method.
scan.close();
}
}
Allow me to rename your boolean variable to letterFound (or maybe even letterFoundInWord2) because this is what you are checking in your double loop. Explanatory naming makes it easier to keep the thoughts clear.
Since you are checking one letter from word1 at a time, you can move the declaration of letterFound inside the outer for loop and initialize it to false here since each time you take a new letter from word1 you haven’t found it in word2 yet. In your if statement inside the for loops, it is correct to break in the case the letters are the same and you set letterFound to true. In the opposite case, don’t break, just go on to check the next letter. In fact you can delete the else part completely.
After the inner for loop, if letterFound is still not true, we know that the letter from word1 is not in word2. So stringCompare() should return false:
if (! letterFound) {
return false;
}
With this change, after the outer for loop we know that all letters from word1 were found in word2, so you can type return true; here.
Except:
You seem to be assuming the strings have the same length. If they have not, you program will not work correctly.
As Andy Turner said, you should also check that all the letters in word2 are in word1; it doesn’t follow from the letters from word1 being in word2.
Should only letters be considered? Should you ignore spaces, digits, punctuation, …?
Hope you will be able to figure it out. Feel free to follow up in comments or ask a new question.
I am solving this question as an assignment of the school. But the two of my test cases are coming out wrong when I submit the code? I don't know what went wrong. I have checked various other test cases and corner cases and it all coming out right.
Here is my code:
public static boolean isPermutation(String input1, String input2) {
if(input1.length() != input2.length())
{
return false;
}
int index1 =0;
int index2 =0;
int count=0;
while(index2<input2.length())
{
while(index1<input1.length())
{
if( input1.charAt(index1)==input2.charAt(index2) )
{
index1=0;
count++;
break;
}
index1++;
}
index2++;
}
if(count==input1.length())
{
return true;
}
return false;
}
SAMPLE INPUT
abcde
baedc
output
true
SAMPLE INPUT
abc
cbd
output
false
A simpler solution would be to sort the characters in both strings and compare those character arrays.
String.toCharArray() returns an array of characters from a String
Arrays.sort(char \[\]) to sort a character array
Arrays.equals(char \[\], char \[\]) to compare the arrays
Example
public static void main(String[] args) {
System.out.println(isPermutation("hello", "olleh"));
System.out.println(isPermutation("hell", "leh"));
System.out.println(isPermutation("world", "wdolr"));
}
private static boolean isPermutation(String a, String b) {
char [] aArray = a.toCharArray();
char [] bArray = b.toCharArray();
Arrays.sort(aArray);
Arrays.sort(bArray);
return Arrays.equals(aArray, bArray);
}
A more long-winded solution without sorting would to be check every character in A is also in B
private static boolean isPermutation(String a, String b) {
char[] aArray = a.toCharArray();
char[] bArray = b.toCharArray();
if (a.length() != b.length()) {
return false;
}
int found = 0;
for (int i = 0; i < aArray.length; i++) {
char eachA = aArray[i];
// check each character in A is found in B
for (int k = 0; k < bArray.length; k++) {
if (eachA == bArray[k]) {
found++;
bArray[k] = '\uFFFF'; // clear so we don't find again
break;
}
}
}
return found == a.length();
}
You have two ways to proceed
Sort both strings and then compare both strings
Count the characters in string and then match.
Follow the tutorial here
In case you String is ASCII you may use the next approach:
Create 256 elements int array
Increment element of corresponding character whenever it's found in string1
Decrement element of corresponding character whenever it's found in string2
If all elements are 0, then string2 is permutation of string1
Overall complexity of this approach is O(n). The only drawback is space allocation for charCount array:
public static boolean isPermutation(String s1, String s2) {
if (s1.length() != s2.length()) {
return false;
}
int[] charCount = new int[256];
for (int i = 0; i < s1.length(); i++) {
charCount[s1.charAt(i)]++;
charCount[s2.charAt(i)]--;
}
for (int i = 0; i < charCount.length; i++) {
if (charCount[i] != 0) {
return false;
}
}
return true;
}
If your strings can hold non-ASCII values, the same approach could be implemented using HashMap<String, Integer> as character count storage
I have a recursive method to solve the permutations problem. I think that this code will seem to be tough but if you will try to understand it you will see the beauty of this code. Recursion is always hard to understand but good to use! This method returns all the permutations of the entered String 's' and keeps storing them in the array 'arr[]'. The value of 't' initially is blank "" .
import java.io.*;
class permute_compare2str
{
static String[] arr= new String [1200];
static int p=0;
void permutation(String s,String t)
{
if (s.length()==0)
{
arr[p++]=t;
return;
}
for(int i=0;i<s.length();i++)
permutation(s.substring(0,i)+s.substring(i+1),t+s.charAt(i));
}
public static void main(String kr[])throws IOException
{
int flag = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the first String:");
String str1 = br.readLine();
System.out.println("Enter the second String:");
String str2 = br.readLine();
new permute_compare2str().permutation(str1,"");
for(int i = 0; i < p; ++i)
{
if(arr[i].equals(str2))
{
flag = 1;
break;
}
}
if(flag == 1)
System.out.println("True");
else
{
System.out.println("False");
return;
}
}
}
One limitation that I can see is that the length of the array is fixed and so will not be able to return values for a large String value 's'. Please alter the same as per the requirements. There are other solution to this problem as well.
I have shared this code because you can actually use this to get the permutations of a string printed directly without the array as well.
HERE:
void permutations(String s,String t)
{
if (s.length()==0)
{
System.out.print(t+" ");
return;
}
for(int i=0;i<s.length();i++)
permutations(s.substring(0,i)+s.substring(i+1),t+s.charAt(i));
}
Value of 's' is the string whose permutations is needed and value of 't' is again empty "".
it will take O(n log n) cuz i sort each string and i used more space to store each one
public static boolean checkPermutation(String a,String b){
return sortString(a).equals(sortString(b));
}
private static String sortString(String test) {
char[] tempChar = test.toCharArray();
Arrays.sort(tempChar);
return new String(tempChar);
}
String checkPermutation(String a,String b){
char[] aArr = a.toCharArray();
char[] bArr = b.toCharArray();
Arrays.sort(aArr);
Arrays.sort(bArr);
if(aArr.length != bArr.length){
return "NO";
}
int p = 0, q = 0;
while(p < aArr.length){
if(aArr[p] != bArr[q]){
return "NO";
}
p++;
q++;
}
return "YES";
}
public static boolean isStringArePermutate(String s1, String s2){
if(s1==null || s2==null) {
return false;
}
int len1 = s1.length();
int len2 =s2.length();
if(len1!=len2){
return false;
}
for(int i =0;i<len1;i++){
if(!s1.contains(String.valueOf(s2.charAt(i)))) {
return false;
}
s1=s1.replaceFirst(String.valueOf(s2.charAt(i)), "");
}
if(s1.equals("")) {
return true;
}
return false;
}