Convert java char inside string to lowerCase/upperCase - java

I have a String called "originalstring" which contains a sentence with mixed upper and lower case characters.
I simply want to flip the string so that if a character is a lowercase make it upper case and vice versa and return it.
I have tried this code, which returns the original string in upperCase:
for (int i = 0; i < originalString.length(); i++) {
char c = originalString.charAt(i);
if (Character.isUpperCase(c)) {
originalString += Character.toLowerCase(c);
}
if (Character.isLowerCase(c)) {
originalString += Character.toUpperCase(c);
}
}
return originalString;

You are adding characters to the original string. Also, this means that your for loop will never get to the end of the iteration of the for loop, because originalString.length() changes each loop also. It's an infinite loop.
Instead, create a StringBuilder that stores the converted characters as you're iterating over the original string. The convert it to a String and return it at the end.
StringBuilder buf = new StringBuilder(originalString.length());
for (int i = 0; i < originalString.length(); i++) {
char c = originalString.charAt(i);
if (Character.isUpperCase(c)) {
buf.append(Character.toLowerCase(c));
}
else if (Character.isLowerCase(c)) {
buf.append(Character.toUpperCase(c));
}
// Account for case: neither upper nor lower
else {
buf.append(c);
}
}
return buf.toString();

Common-lang provide a swapCase function, see the doc. Sample from the doc:
StringUtils.swapCase(null) = null
StringUtils.swapCase("") = ""
StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
And if you really want to do it by yourself, you can check the source of common-lang StringUtils

Instead of using existing utilities, you may try below conversion using boolean operation:
To upper case:
char upperChar = (char) (c & 0x5f)
To lower case:
char lowerChar = (char) (c ^ 0x20)
In your program:
StringBuilder result = new StringBuilder(originalString.length());
for (int i = 0; i < originalString.length(); i++) {
char c = originalString.charAt(i);
if (Character.isUpperCase(c)) {
result.append((char) (c ^ 0x20));
}
else if ((c >= 'a') && (c <= 'z')) {
result.append((char) (c & 0x5f));
}
else {
result.append(c);
}
}
System.out.println(result);

Related

Trying to change a string to altcase

Trying to write a code that makes a string become altcase (ie. "hello" becomes "HeLlO". I borrowed code from another question on this forum that asked for something similar (Java Case Switcher) However, the code only switched the casing of a letter instead of having a capital letter (first), then lowercase letter, etc. pattern.
What I have so far:
public String altCase(String text)
{
String str = "";
for (int i = 0; i <= text.length(); i++)
{
char cA = text.charAt(i);
if (text.charAt(0).isUppercase)
{
str += Character.toLowerCase(cA);
}
if (text.charAt(0).isLowercase)
{
str += Character.toUpperCase;
}
if(i != 0 && Character.isUpperCase(cA))
{
if (text.charAt(i)-1.isUpperCase || text.charAt(i)+1.isUpperCase)
{
str += Character.toLowerCase(cA);
}
else
{
str += cA;
}
}
if(i != 0 && Character.isLowerCase(cA))
{
if (text.charAt(i)-1.isLowerCase || text.charAt(i)+1.isLowerCase)
{
str += Character.toUpperCase(cA);
}
else
{
str += cA;
}
}
}
return str;
}
I'm still relatively new to coding in general so please excuse my inefficiencies, as well as any headaches I might induce from the lack of experience in my coding. I cannot tell where I am going wrong except maybe when I typed "text.charAt(i)-1.isLowerCase" as the statement seems a bit illogical, but I am lost in terms of trying to come up with something else that would accomplish the same thing. Or is my error completely elsewhere? Thanks for any help in advance.
The modulus operator could take you a long way here...
StringBuilder rslt = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
switch (i % 2) {
case 0:
rslt.append(Character.toUpperCase(c));
break;
case 1:
rslt.append(Character.toLowerCase(c));
break;
}
}
return rslt.toString();
If I truly understand what you want to get is that:
Get a string, change it in a format of AbCdEfG.... and so on.
There is more simple solution.
Get a string and with for loop, for every character, change character size depending on position in string, for i%2 == 0 upper case, and i%2 == 1 lower case.
public String altCase(String text)
{
String str = "";
for (int i = 0; i < text.length(); i++)
{
char cA = text.charAt(i);
if (i%2 == 0)
{
str += Character.toUpperCase(cA);
}
else
{
str += Character.toLowerCase(cA);
}
}
return str;
}
I would start with a StringBuilder (a mutable character sequence) of text.toLowerCase(); then set the characters at even indices to their capital equivalents (and your method doesn't appear to depend on instance state, so it might be static). Something like,
public static String altCase(String text) {
StringBuilder sb = new StringBuilder(text.toLowerCase());
for (int i = 0; i < text.length(); i += 2) {
sb.setCharAt(i, Character.toUpperCase(sb.charAt(i)));
}
return sb.toString();
}
IntStream.range(0, s.length()).mapToObj(i -> i % 2 == 0 ?
Character.toUpperCase(s.charAt(i)) :
Character.toLowerCase(s.charAt(i)))
.map(String::valueOf)
.collect(Collectors.joining());

Check if a String has vowels, and create a new String that doubles the consonants

So here's what I'm trying to do. I take a given string, and make a new string. The new string will be the same as the original string, but will have the consonants doubled.
For example, rabbit becomes rrabbitt and so forth. It only doubles the consonants that aren't already doubled.
Here's what I have so far:
// Returns a new string in which all consonants in the given string are doubled.
// Consonants that are already doubled are not doubled again.
// For example, doubleConsonants("rabbit") returns "rrabbitt".
// It is assumed that in the given string is alphabetic and that no character
// appears more than twice in a row.
// Parameters:
// s - given string
// Returns new string with all consonants doubled
----------------------------------------------------------------------------
public static String doubleConsonants(String s) {
String newString = "";
String vowels = "aeiouAEIOU";
for (int i = 0; i < s.length(); i++) {
boolean hasVowel = false;
for (int n = 0; n == 10; n++){
if ( vowels.charAt(n) == s.charAt(i)) {
newString += s.charAt(i);
i++;
hasVowel = true;
break;
}
}
if (hasVowel = false && s.charAt(i) != s.charAt(i+1) && s.charAt(i) != s.charAt(i-1)) {
newString += s.charAt(i);
i++;
}
else if (hasVowel = false) {
newString += s.charAt(i);
i++;
}
}
return newString;
}
Apparently there are some issues with "dead code" and the boolean hasVowels is "not used". What am I screwing up?
You can do one thing. Using a contains() method will greatly reduce all your work.
for (int i = 0; i < s.length(); i++) { // traverse through the string
if (i < s.length() - 1 && s.charAt(i) == s.charAt(i + 1)) {
newString += s.charAt(i); // handles the double constant special condition like bb in rabbit
i++;
} else if (vowels.contains("" + s.charAt(i))) { //check if the letter is a vowel
newString += s.charAt(i); // if yes, add it once
} else {
newString += "" + s.charAt(i) +s.charAt(i); // else add it twice
}
}
At the end of this code block, you will have the required string stored in newString. you can read more about contains()
Try this.
public static String doubleConsonants(String s) {
return s.replaceAll("(?i)(([^aeiou])\\2+)|([^aeiou])", "$1$3$3");
}
First thing I notice is that the if-statements towards the bottom are using the assignment operator. You want to use the double-equals to test the value. I'll have to look more closely at the logic for more.

Read 2 letters in a string using JAVA

I need to write a Java program that reads a string and determines if there are these two letters: the lowercase letter “e” or “d”.
That's what i written so far! any ideas why this doesn't work?
class ex2 {
public static void main(String[] args) {
//boolean arg1;
char e = 'e';
char d = 'd';
String x = "This is my test";
char[] xh = new char[x.length()];
for(int i=0; i<= x.length();i++) {
if (xh[i] == e || xh[i] == d) {
// arg1 = true;
System.out.println("Correct"); // Display he string
} else {
//arg1 = false;
System.out.println("Wrong");
}
}
}
}
First you have an ArrayOutOfBound exception because you need to stop just before the length, i.e. i<x.length().
Now your problem is that you test against an array of char that is full of null chars. You need to test against the string :
if (x.charAt(i) == e || x.charAt(i) == d) {
You never put anything in your array. char[] xh = new char[x.length()]; simply declares an array of length equal to x, it does not set the elements of xh to the elements of x. Instead, use:
char[] xh = x.toCharArray();
You also need to change your loop to:
for(int i=0; i < x.length(); i++) {
to avoid the out of bounds exception you are currently seeing.
Your main problem is the fact that you don't properly iterate over the char of your String, here is the best way to do it:
for (int i = 0, length = x.length(); i < length; i++) {
char c = x.charAt(i);
...
}
Assuming that you use Java 8, you could rely on the Stream API to do the same thing as next:
boolean result = x.chars().anyMatch(c -> c == 'e' || c == 'd');
this is the simple solution if you want to use it
NOTE from comments, you must keep account that if there is no e and d, this will iterate twice on the content of the String but not is second code as second example is just short form of for each
String str = "ewithd";
if (str.contains("e") || str.contains("d")) {
System.out.println("sucess");
} else
System.out.println("fail");
if you want to go with array then you can use foreach() too
char[] ch = str.toCharArray();
for (char c : ch) {
if (c == 'e' || c == 'd') {
System.out.println("success");
else
System.out.println("fail");
}
}

ASCII to HTML-Entities Escaping in Java

I found this website with escape codes and I'm just wondering if someone has done this already so I don't have to spend couple of hours building this logic:
StringBuffer sb = new StringBuffer();
int n = s.length();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
switch (c) {
case '\u25CF': sb.append("●"); break;
case '\u25BA': sb.append("►"); break;
/*
... the rest of the hex chars literals to HTML entities
*/
default: sb.append(c); break;
}
}
These "codes" is a mere decimal representation of the unicode value of the actual character. It seems to me that something like this would work, unless you want to be very strict about which codes get converted, and which don't.
StringBuilder sb = new StringBuilder();
int n = s.length();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if (Character.UnicodeBlock.of(c) != Character.UnicodeBlock.BASIC_LATIN) {
sb.append("&#");
sb.append((int)c);
sb.append(';');
} else {
sb.append(c);
}
}
The other answers don't work correctly for surrogate pairs, e.g. if you have Emojis such as "😀" (see character info). Here's how to do it in Java 8:
StringBuilder sb = new StringBuilder();
s.codePoints().forEach(codePoint -> {
if (Character.UnicodeBlock.of(codePoint) != Character.UnicodeBlock.BASIC_LATIN) {
sb.append("&#");
sb.append(codePoint);
sb.append(';');
} else {
sb.appendCodePoint(codePoint);
}
});
And for older Java:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); ) {
int c = s.codePointAt(i);
if (Character.UnicodeBlock.of(c) != Character.UnicodeBlock.BASIC_LATIN) {
sb.append("&#");
sb.append(c);
sb.append(';');
} else {
sb.appendCodePoint(c);
}
i += Character.charCount(c);
}
A simple way to test if a solution handles surrogate pairs correctly is to use "\uD83D\uDE00" (😀) as the input. If the output is "😀", then it's wrong. The correct output is 😀.
Hmm, what if you did something like this instead:
if (c > 127) {
sb.append("&#" + (int) c + ";");
} else {
sb.append(c);
}
Then you just need to determine the range of characters you want HTML escaped. In this case I just specified any character beyond the ASCII table space.

Increase string value

Java question here:
If i have a string "a", how can I "add" value to the string, so I get a "b" and so on?
like "a++"
String str = "abcde";
System.out.println(getIncrementedString(str));
Output
bcdef
//this code will give next char in unicode sequence
public static String getIncrementedString(String str){
StringBuilder sb = new StringBuilder();
for(char c:str.toCharArray()){
sb.append(++c);
}
return sb.toString();
}
If you use the char primitive data type you can accomplish this:
char letter = 'a';
letter++;
System.out.println(letter);
prints out b
i made some changes to te paulo eberman code, to handle digits and characters, if valuable for someone i share this mod....
public final static char MIN_DIGIT = '0';
public final static char MAX_DIGIT = '9';
public final static char MIN_LETTER = 'A';
public final static char MAX_LETTER = 'Z';
public String incrementedAlpha(String original) {
StringBuilder buf = new StringBuilder(original);
//int index = buf.length() -1;
int i = buf.length() - 1;
//while(index >= 0) {
while (i >= 0) {
char c = buf.charAt(i);
c++;
// revisar si es numero
if ((c - 1) >= MIN_LETTER && (c - 1) <= MAX_LETTER) {
if (c > MAX_LETTER) { // overflow, carry one
buf.setCharAt(i, MIN_LETTER);
i--;
continue;
}
} else {
if (c > MAX_DIGIT) { // overflow, carry one
buf.setCharAt(i, MIN_DIGIT);
i--;
continue;
}
}
// revisar si es numero
buf.setCharAt(i, c);
return buf.toString();
}
// overflow at the first "digit", need to add one more digit
buf.insert(0, MIN_DIGIT);
return buf.toString();
}
i hope be usefull for someone.
use this code to increment char value by an integer
int a='a';
System.out.println("int: "+a);
a=a+3;
char c=(char)a;
System.out.println("char :"+c);
Convert the string to a char.
Increment the char.
Convert the char
back to a string.
Example:
//convert a single letter string to char
String a = "a";
char tmp = a.charAt(0);
//increment char
tmp++;
//convert char to string
String b = String.valueOf(tmp);
System.out.println(b);
Assuming you want something like aaab => aaac and not => bbbc, this would work:
public String incremented(String original) {
StringBuilder buf = new StringBuilder(original);
int index = buf.length() -1;
while(index >= 0) {
char c = buf.charAt(i);
c++;
buf.setCharAt(i, c);
if(c == 0) { // overflow, carry one
i--;
continue;
}
return buf.toString();
}
// overflow at the first "digit", need to add one more digit
buf.insert(0, '\1');
return buf.toString();
}
This treats all characters (in fact char values) the same, and fails (does strange stuff) for some unicode code-points outside the first plane (which occupy two char values in a String).
If you only want to use english lowercase letters as digits, you can try this variant:
public final static char MIN_DIGIT = 'a';
public final static char MAX_DIGIT = 'z';
public String incrementedAlpha(String original) {
StringBuilder buf = new StringBuilder(original);
int index = buf.length() -1;
while(index >= 0) {
char c = buf.charAt(i);
c++;
if(c > MAX_DIGIT) { // overflow, carry one
buf.setCharAt(i, MIN_DIGIT);
i--;
continue;
}
buf.setCharAt(i, c);
return buf.toString();
}
// overflow at the first "digit", need to add one more digit
buf.insert(0, MIN_DIGIT);
return buf.toString();
}
This does a => b => c, y => z => aa => ab.
if you want to do more calculation with the string, consider staying with StringBuilder (or StringBuffer for multithreaded access) instead of repeatedly copying between String and StringBuilder.
Or use a class made to do this, like BigInteger.

Categories