So I'm writing a little return program that switches the case of characters in a string, so HELLo becomes hElLo and hello becomes HeLlO, and aaa becomes AaA. I'm having a bit of trouble though. I'm still new and learning java, so sorry if this breaks rules:
public static String altCase(String text){
String str = "";
for (int i = 0; i <= text.length()-1; i++)
{
char ch = text.charAt(i);
boolean lastIsUpperCase = true;
if(Character.isUpperCase(i-1))
{
lastIsUpperCase = true;
}
else if(Character.isLowerCase(i-1))
{
lastIsUpperCase = false;
}
if(lastIsUpperCase)
{
str += Character.toLowerCase(ch);
}
else if (!lastIsUpperCase)
{
str += Character.toUpperCase(ch);
}
}
return str;
}
You should add the char to your if clause as in:
String str = "";
for (int i = 0; i <= text.length()-1; i++)
{
char ch = text.charAt(i);
if(Character.isUpperCase(ch))
{
str += Character.toLowerCase(ch);
}
else if(Character.isLowerCase(ch))
{
str += Character.toUpperCase(ch);
}
}
return str;
}
I would use a StringBuilder to build up the return value, and you could also use a String.toCharArray() and a for-each loop. Finally, you can test if a character is lower case (or upper case) and then swap the case. Something like,
public static String altCase(String text) {
if (text == null || text.isEmpty()) {
return text;
}
StringBuilder sb = new StringBuilder(text.length());
for (char ch : text.toCharArray()) {
if (Character.isUpperCase(ch)) {
sb.append(Character.toLowerCase(ch));
} else if (Character.isLowerCase(ch)) {
sb.append(Character.toUpperCase(ch));
} else {
sb.append(ch);
}
}
return sb.toString();
}
You could make a char array and then check and swap each element individually. When you are done just pass that char array to a string as argument to make it into a string
char[] word = new char[3];
String str = new String(word);
So I managed to do it.
public static String altCase(String text){
String str = "";
str += Character.toUpperCase(text.charAt(0));
for (int i = 1; i <= text.length()-1; i++)
{
char ch = text.charAt(i);
boolean lastUp = flipFlop(i);
char temp = switcher(ch, lastUp);
str+=temp;
}
return str;
}
public static boolean flipFlop (int i){
boolean bool = true;
if(i==1){
bool = true;
}
else if((i%2)==0)
{
bool = false;
}
else if((i%2)!=0)
{
bool = true;
}
return bool;
}
public static char switcher (char ch, boolean lastUp){
char temp = ch;
if(lastUp){
temp = Character.toLowerCase(ch);
}
else if (lastUp==false){
temp = Character.toUpperCase(ch);
}
return temp;
}
I added a 'flipFlop' method to track the iterations, and the method 'switcher' changes between upper and lower case based on the condition of the last char. (lastUp is true when the last character in the string is uppercase).
Related
You are allowed to use the following methods from the Java API:
class String:
length,charAt
class StringBuilder:
length,charAt,append,toString
class Character: any method
moveAllXsRight takes a char and a String as input and returns a String.
The output string should be the same as the input string except that every occurrence of the input character should be shifted one character to the right. If it is impossible to shift a character to the right (it is at the end of the string), then it is not shifted. Do not use arrays to solve this problem.
HW2.moveAllXsRight('X', "abcXdeXXXfghXiXXjXX")
"abcdXefXXXghiXjXXXX"
Here is my code now:
public static String moveAllXsRight(char a, String b){
StringBuilder sb = new StringBuilder();
String str ="";
for ( int i = 0; i<b.length(); i++){
if(b.charAt(i) != a){
sb.append(b.charAt(i));
}
else if(b.charAt(i) == a){
str = Character.toString(b.charAt(i));
}
else {
if(b.charAt(i+2)>sb.length()){
sb.append(b.charAt(i));
}
}
}
return sb.toString();
}
Try this:
public static String moveAllXsRight(char a, String b) {
StringBuilder sb = new StringBuilder(b);
for(int i = 0; i < sb.length() - 1; i++) {
if(sb.charAt(i) == a) {
// swapping with the right character
sb.setCharAt(i, sb.charAt(i + 1));
sb.setCharAt(i + 1, a);
// skipping next index (because we already know it contains `a`)
i = i + 1;
}
}
return sb.toString();
}
For this example:
moveAllXsRight('X', "abcXdeXXXfghXiXXjXX");
This is the output:
abcdXeXXfXghiXXXjXX
Update:
By slightly changing the for loop (inverting it):
for(int i = sb.length() - 2; i > 0; i--) { // inverse loop
if(sb.charAt(i) == a) {
// swapping
sb.setCharAt(i, sb.charAt(i + 1));
sb.setCharAt(i + 1, a);
}
}
Now this:
moveAllXsRight('X', "abcXdeXXXfghXiXXjXX");
Results in:
abcdXefXXXghiXjXXXX
Now you can decide which version do you want to use.
Here's one way to do it:
public static String moveAllXsRight(char a, String b) {
char[] chars = b.toCharArray();
for (int i = 0; i < chars.length-1; ++i) {
if (chars[i] == a) {
chars[i] = chars[i+1];
chars[i+1] = a;
}
}
return new String(chars);
}
It gives "abcdeXXXfghXiXXjXXX" when the arguments are 'X' and "abcXdeXXXfghXiXXjXX".
Here's another way:
public static String moveAllXsRight(char a, String b) {
char[] chars = b.toCharArray();
boolean wasa = false;
for (int i = 0; i < chars.length; ++i) {
char c = chars[i];
if (wasa) {
chars[i-1] = c;
chars[i] = a;
}
wasa = c == a;
}
return new String(chars);
}
It gives "abcdXeXXfXghiXXjXXX".
UPDATE
Here's yet another way:
public static String moveAllXsRight(char a, String b) {
char[] chars = b.toCharArray();
for (int i = chars.length-1; --i >= 0;) {
char c = chars[i];
if (c == a) {
chars[i] = chars[i+1];
chars[i+1] = a;
}
}
return new String(chars);
}
It gives "abcdXefXXXghiXjXXXX" which is what you expected.
UPDATE 2:
With a StringBuilder to avoid using arrays:
public static String moveAllXsRight(char a, String b) {
StringBuilder buf = new StringBuilder(b);
for (int i = buf.length()-1; --i >= 0;) {
char c = buf.charAt(i);
if (c == a) {
buf.setCharAt(i, buf.charAt(i+1));
buf.setCharAt(i+1, a);
}
}
return buf.toString();
}
public static String moveAllXsRight(char a, String b){
String str ="";
int n = 0;
char lower_a = Character.toLowerCase(a);
char upper_a = Character.toUpperCase(a);
for ( int i = b.length()-2; i>=0; i--){
if(b.charAt(i) == lower_a || b.charAt(i) == upper_a){
n++;
}
}
str = b.substring(b.length()-n) + b.substring(0,b.length()-n);
return str;
}
I'm trying to make altcase.
Most of the program works except where I ad the strings together on both the if and else statement. (where newstr = newstr....)
If this were to run, it should output
'I HoPe aLtCaSe wOrKs'
public class tester {
public static void main(String[] args) {
System.out.println(altCase("i hope altcase works"));
}
public static String altCase(String text)
{
int COUNT = text.length();
char c;
int check = 0;
String newstr = "";
for (int i = 0; i < COUNT; i++)
{
c = text.charAt(i);
if(check == 0) {
c = c.toUpperCase();
newstr = newstr + c;
check++;
}
else {
c = c.toLowerCase();
newstr = newstr + c;
check--;
}
}
return newstr;
}
}
The code should be like this
public static void main(String[] args) {
System.out.println(altCase("i hope altcase works"));
}
public static String altCase(String text)
{
int COUNT = text.length();
char c;
int check = 0;
String newstr = "";
for (int i = 0; i < COUNT; i++)
{
c = text.charAt(i);
if(c==' ') {
newstr = newstr + c;
continue;
}
if(check == 0) {
c = (char)(c-32);
newstr = newstr + c;
check++;
}
else {
newstr = newstr + c;
check--;
}
}
return newstr;
}
If you need a solution without using toUpperCase() or toLowerCase(), I suggest you to try this out.
public class Tester {
public static void main(String[] args) {
System.out.println(altCase("i hope altcase works"));
}
public static String altCase(String text) {
char[] array = text.toCharArray();
text ="";
for (int i = 0; i < array.length; i++) {
text += (i%2!=0)?array[i]:Tester.utilityToUpper(array[i]);
}
return text;
}
public static char utilityToUpper(char i){
return (char) ((i!=' ')? (i - 32) : i);
}
}
I would call String.toCharArray() and then convert even indices to uppercase with Character.toUpperCase(char) and odd indices to lowercase with Character.toLowerCase(char). Finally, return a new String based on the updated char[]. Like,
public static String altCase(String text) {
char[] arr = text.toCharArray();
for (int i = 0; i < arr.length; i++) {
if (i % 2 == 0) {
arr[i] = Character.toUpperCase(arr[i]);
} else {
arr[i] = Character.toLowerCase(arr[i]);
}
}
return new String(arr);
}
On reflection, we can improve that by converting the input to upper case first, and then only changing odd elements to lower-case. Like,
public static String altCase(String text) {
char[] arr = text.toUpperCase().toCharArray();
for (int i = 1; i < arr.length; i += 2) {
arr[i] = Character.toLowerCase(arr[i]);
}
return new String(arr);
}
I'm assuming input isn't always strictly lower-case. If it is, then it would be trivial to skip the up-front case conversion and apply the same approach to the even indices. Like,
public static String altCase(String text) {
char[] arr = text.toCharArray();
for (int i = 0; i < arr.length; i += 2) {
arr[i] = Character.toUpperCase(arr[i]);
}
return new String(arr);
}
I'm dealing with logical expressions in strings. So far I have worked on the following method.
public static String modify(String expression)
{
String temp = expression;
String validated = "";
for(int idx=0; idx<temp.length(); idx++)
{
if(idx!=temp.length()-1)
{
if((Character.isAlphabetic(temp.charAt(idx))) && (Character.isAlphabetic(temp.charAt(idx+1))))
{
validated+=temp.substring(idx,idx+1);
validated+="*";
}
else
validated+=temp.substring(idx,idx+1);
}
else
validated+=temp.substring(idx);
}
return validated;
}
The following are examples of supposed input/output
input: AB+BC+ABC / output: (A*B)+(B*C)+(A*B*C)
input: (A+B)+ABC / output: (A+B)+(A*B*C)
input: (A+B)*(B+C)*(AB) / output: (A+B)*(B+C)*(A*B)
One way you can do it is simply keeping track of brackets with a boolean semaphore
public static String modify(String expression)
{
String temp = expression;
StringBuilder validated = new StringBuilder();
boolean inBrackets=false;
for(int idx=0; idx<temp.length()-1; idx++)
{
if((Character.isLetter(temp.charAt(idx))) && (Character.isLetter(temp.charAt(idx+1))))
{
if(!inBrackets){
inBrackets = true;
validated.append("(");
}
validated.append(temp.substring(idx,idx+1));
validated.append("*");
}
else{
validated.append(temp.substring(idx,idx+1));
if(inBrackets){
validated.append(")");
inBrackets=false;
}
}
}
validated.append(temp.substring(temp.length()-1));
if(inBrackets){
validated.append(")");
inBrackets=false;
}
return validated.toString();
}
Also never use string concatenation instead use StringBuilder or its predecessor StringBuffer in case you are seeking thread safe solution.
Here is what I would do, using StringBuilder and a split:
public static String modify(String expression)
{
StringBuilder finalString = new StringBuilder();
String[] subExpressions = expression.split("\\+");
List<String> formattedSubExpressions = new ArrayList<String>();
for (String subExpression : subExpressions) {
if (subExpression.length() > 1) {
StringBuilder formattedSubExpression = new StringBuilder();
formattedSubExpression.append("(");
for (int i=0; i<subExpression.length(); i++) {
formattedSubExpression.append(subExpression.charAt(i));
if (i != subExpression.length() -1 ) {
formattedSubExpression.append("*");
}
}
formattedSubExpression.append(")");
formattedSubExpressions.add(formattedSubExpression.toString());
} else {
formattedSubExpressions.add(subExpression);
}
}
for (String subExpression : formattedSubExpressions) {
finalString.append(subExpression);
finalString.append("+");
}
if (finalString.charAt(finalString.length() - 1) == '+') {
finalString.deleteCharAt(finalString.length() - 1);
}
return finalString.toString();
}
It gives the following sample input/output:
AB+CD: (A*B)+(C*D)
AB+CD+EF: (A*B)+(C*D)+(E*F)
AB+CD+EFGH: (A*B)+(C*D)+(E*F*G*H)
I based this answer on the idea that what you want to do is group repeating alpha characters between parentheses and put an asterisks between them regardless of the operation (add, subtract, divide, etc) being performed between the groups.
private static final Pattern p = Pattern.compile("[a-zA-Z]{2,}");
public String parse(String s){
if(s == null || "".equals(s)) {
return s;
}
char[] chars = s.toCharArray();
StringBuilder sb = new StringBuilder(100);
Matcher m = p.matcher(s);
int i = 0;
while(i<chars.length && m.find()){
int startIdx = m.start();
int endIdx = m.end();
// Need to get the leading part of the string before this matching region
while(i < startIdx){
sb.append(chars[i]);
i++;
}
sb.append('('); // Start getting the match region
while(i < endIdx){
sb.append(chars[i]);
if(i < endIdx - 1){
sb.append('*');
}
i++;
}
sb.append(')'); // end the match region
}
// If there is a region beyond the last match, append it
if(i < chars.length -1){
for(; i < chars.length; i++){
sb.append(chars[i]);
}
}
return sb.toString();
}
Using a for loop, how do I go about making all consonants in a string uppercase?
I think I should do something like this:
String str = "fish$"
String strConsonants = "f, s, h";
for (int x = 0; x < str.length(); x++)
{
if(((str.charAt(x) == (strConsonants))
{
System.out.print("FiSH$");
}
}
use String.contains() method from String API. the followingcode would work for your present input. usually, if you want to find all the consonents, have an char[] of consonents or String with all the consonents and do the check.
String str = "fish$";
String strConsonants = "f, s, h";
String temp="";
for (int x = 0; x < str.length(); x++){
temp+= str.charAt(x);
if(!strConsonants.contains(temp)) {
consonentsUCase+=temp.toUpperCase();
}
temp="";
}
I've just written it.
Output: FiSH$
Works for any word ! ;)
API method: printStringWithUpperConsonant
import java.util.HashSet;
import java.util.Set;
public class ConsonantUtils {
private Set<Character> vowels = getVowels();
private String analysedString;
public ConsonantUtils(String analysedString) {
this.analysedString = analysedString;
}
public static void main(String[] args) {
new ConsonantUtils("fish$").printStringWithUpperConsonant();
}
public void printStringWithUpperConsonant() {
for (int i = 0; i < getAnalysedString().length(); i++) {
printChar(getCurrentChar(i));
}
}
private char getCurrentChar(int i) {
return getAnalysedString().charAt(i);
}
private void printChar(char currentChar) {
if (isConsonant(currentChar)) {
System.out.print(makeCharUpperCase(currentChar));
}
else{
System.out.print(currentChar);
}
}
private Set<Character> getVowels() {
Set<Character> vowels = new HashSet<Character>();
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
return vowels;
}
private char makeCharUpperCase(char character) {
return Character.toUpperCase(character);
}
private boolean isConsonant(char currentChar) {
return !vowels.contains(currentChar);
}
private String getAnalysedString(){
return analysedString;
}
}
You can use Character.toUpperCase().
String vowels = "aeiouAEIOU";
char[] charArr = str.toCharArray(); //turn the string into char array
for(int i=0; i<charArr.length; i++) { //for loop
if(vowels.indexOf(charArr[i]) == -1) { // if not a vowel
charArr[i] = Character.toUpperCase(charArr[i]); //replace with upper case
}
}
Sting rslt = String.valueOf(charArr); //finally turn the array back to string
String str = "fish$";
String strVowels = "aeiouAEIOU";
String out = "";
for (Character c : str.toCharArray())
{
if(!strVowels.contains(""+c))
{
out = out + Character.toUpperCase(c);
}
else
{
out = out + c;
}
}
System.out.println(out);
This works for me:
List<Character> constants = Arrays.asList('f', 's', 'h');
String str = "fish$";
for (Character c : constants) {
str = str.replace(c, Character.toUpperCase(c));
}
I am attempting to solve a codingbat problem called mirrorEnds. My solution fails but I'm not getting any useful feedback from the site, only a failed test run:
And my code (I changed string to str cause I'm used to the problems with "str"):
public String mirrorEnds(String string) {
String str = string;
StringBuilder sb = new StringBuilder();
int beg = 0;
int end = str.length()-1;
while(beg < end)
{
if(str.charAt(beg)==str.charAt(end))
sb.append(str.substring(beg,beg+1));
else
break;
++beg;
--end;
}
if(beg==end)
return str;
else
return sb.toString();
}
Here's mine, for what it's worth (not much, I know, but I was writing it while you were finding the bug..)
private String mirrorEnds(String string) {
final char[] chars = string.toCharArray();
final int n = chars.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
if (chars[i] != chars[n - i - 1])
break;
sb.append(chars[i]);
}
return sb.toString();
}
Bah. I found it. Instance is "abba"
Needed to change "if(beg==end)" to "if(beg>=end)".
public String mirrorEnds(String string) {
String s = "";
String str = "";
for (int i=string.length()-1; i>=0; i--)
{
s = s + string.charAt(i);
}
for (int j=0; j<string.length(); j++)
{
if (s.charAt(j) == string.charAt(j))
{
str = str + string.charAt(j);
}
if (s.charAt(j) != string.charAt(j))
{
break;
}
}
return str;
}
public static String mirrorEnds(String string) {
for (int i = 0; i < string.length(); i++) {
if(string.charAt(i) != string.charAt(string.length()-i-1)){
return string.substring(0,i);
}
else if(i==string.length()-1) return string;
}
return "";
}
Making a helper method is both efficient and makes the job easier, and logic clearer, recommended strategy for beginners, dissect the logic out, then put it together, as seen in codingBat's fizzBuzz questions that build up to the real fizzBuzz. Even though there a shorter solutions, this shows the full extent of logic used.
public String mirrorEnds(String string) {
String reversed = reverseString(string); //the reversed version
String result = "";
for(int a = 0; a < string.length(); a++){
if(string.charAt(a) == reversed.charAt(a)){ //keep going...
result += string.charAt(a);
}
else if(string.charAt(a) != reversed.charAt(a)){
break; //error, stop
}
}
return result;
}
public String reverseString(String s){
String reversed = "";
for(int a = s.length() - 1; a >= 0; a--){
reversed += s.charAt(a);
}
return reversed;
}
Here is mine:
public String mirrorEnds(String str) {
String res = "";
int count = str.length() - 1;
for(int i = 0;i < str.length();i++)
{
if(str.charAt(i) == str.charAt(count))
res += str.substring(i, i + 1);
else
break;
count--;
}
return res;
}
Here's my solution, hope it can help you
public String mirrorEnds(String string) {
int mid = string.length() / 2;
String s = "";
for (int i = 0, j = string.length()-1; i <= mid; i++, j--) {
if (i == mid) {
return string;
}
if (string.charAt(i) == string.charAt(j)) {
s += string.charAt(i) + "";
} else {
break;
}
}
return s;
}
Here's mine. I did mine a little bit different.
public String mirrorEnds(String string) {
//Create a string that we will eventually return.
String ret = "";
//Create a for loop that takes in chars from both ends.
for (int i = 0; i < string.length(); i++)
{
//Create one and two characters in order to simplify it.
char one = string.charAt(i);
char two = string.charAt(string.length() - 1 - i);
//If the front and back character in the iteration
//equal each other, then we add the character to the return string.
if (one == two)
{
ret = ret + one;
}
//Otherwise, we end the loop because we don't want to
//Have a loopback problem.
else
{
break;
}
}
//Return the string that we are working on.
return ret;
}