How to turn uppercase to lowercase using the charAt method? - java

I need to create a function that will make all uppercase characters lowercase using the charAt method. I've tried to use typecasting to change the int values to char but got lost after that.
/********************************************************************************
This function will calculate the integer average of characters in the array
********************************************************************************/
public static void lowerCase(char[] letter) {
char mean;
mean = (char) ((int) ch + 32);
}

Oh, actually you don't need to check it using charAt. Just convert everything to lowercase. That will not affect the character that are already in lowercase, and convert the uppercase characters to lowercase. That's what you need.
You don't need to convert your character array to string object and then use String.toLowerCase method, because it internally uses Character.toLowerCase method only.
public static void average( char [] letter ) {
for (int i = 0; i < letter.length; i++) {
letter[i] = Character.toLowerCase(letter);
}
System.out.println(Arrays.toString(letter));
}

If you like to use only charAt, you can try:
String test = "fasdWADFASD242134";
StringBuilder result = new StringBuilder(test);
for (int i = 0; i < test.length(); i++) {
char ch = test.charAt(i);
result.setCharAt(i, ch >= 'A' && ch <= 'Z' ? (char) (ch + 'a' - 'A') : ch);
}
System.out.println("result = " + result);
If you have an char array, you can use:
public static void toLower(char[] letter){
for (int i = 0; i < letter.length; i++) {
char ch= letter[i];
letter[i]= ch >= 'A' && ch <= 'Z' ? (char) (ch + 'a' - 'A') : ch;
}
}

If you dont have to use charAt()...
public static void average( char [] letter )
{
String str = new String(letter);
System.out.println("The value is "+str.toUpperCase());
}

Assuming you want to process the characters individually (like a charAt):
char c = letter[i]; // i = 0...len(letter-1)
char upperC = Character.toLowerCase(c);
If you don't actually want to use charAt:
String lowerCaseVersion = (new String(letter)).toLowerCase();

Try this one, looks like a working method
http://www.techlabs4u.com/2011/07/java-code-to-convert-string-to-lower.html

Just do like this:
String string = "some string";
System.out.println(string.toUpperCase());
String class has a method toUpperCase() and also toLowerCase(), which you can use to transform you String into upper or lower case letters and you don't need to use charAt method (in case you need to transform the specific letter).

"abcdefghijklmnopqrstuvwxyz".charAt(character - 'A')

Related

Incorrect output in small program. Why is this String variable not doing what I want it to?

This program should take a String, check if each letter is a vowel and change the vowels into underscores. For example, if I enter some it should output s_m_. This is a simple programming exercise that I feel like I should be able to do. However I am genuinely stumped and can't tell what I'm doing wrong.
I have declared an array to keep the vowels, a newStr variable which will contain the updated string ,and I'm looping through the string, comparing each letter using charAt() to check if it's in the vowels array. If it is, I add _ to the updated String, and I keep the original letter if it's not. The final output is wrong, what am I doing wrong?
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
String newStr = "";
for (int x = 0; x < str.length(); x++) {
char letter = str.charAt(x);
for (int j = 0; j < vowels.length; j++) {
if (letter == vowels[j]) {
newStr = newStr + '_';
break;
} else {
newStr = newStr + letter;
break;
}
}
}
out.println(newStr);
In your code the issue is within your nested "for-loop". I say this in quotes because it never actually loops. The first iteration j=0 immediately breaks the loop since either your letter is equal to a with (letter == vowels[0]) or not. In either case you do a break; and append the character. This means your loop can be reduced to a simple if-else that checks if the letter is an a and replaces it with _ or keeps it.
To fix this issue you need to use a different approach. You can create a String of vowels such as "aeiouAEIOU" and use indexOf to test whether the selected character is a vowel.
public static String omitVowels(String input) {
StringBuilder out = new StringBuilder(input.length());
String vowels = "aeiouAEIOU";
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (vowels.indexOf(c) >= 0) // is vowel if index not negative
out.append('_');
else
out.append(c);
}
return out.toString();
}
indexOf(char) will return -1 if the provided character is not part of the string, else it will return the specific index. We can use this property to test whether the character is a vowel or not.
Examples
omitVowels("hello world") -> "h_ll_ w_rld"
omitVowels("aeiou") -> "_____"
omitVowels("TESTing") -> "T_ST_ng"
This is pretty simple. Just iterate over each character of the given string and replace with _ in case of it is vowel.
Use StringBuilder
Be ware of using String. This is immutable in java, therefore to build final string, you should use StringBuilder.
public static String replaceVowel(String str) {
final IntPredicate isVowel = ch -> ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
StringBuilder buf = new StringBuilder(str.length());
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
boolean vowel = isVowel.test(Character.toLowerCase(ch));
buf.append(vowel ? '_' : ch);
}
return buf.toString();
}
Use RegularExpression
As alternative, you can use Regular Expression with replaceAll() method of the String class.
private static final Pattern VOWEL = Pattern.compile("[aeiou]");
public static String replaceVowel(String str) {
return VOWEL.matcher(str).replaceAll("_");
}
This is also correct, because in the background, replaceAll() uses StringBUilder.
for (int x = 0; x < str.length(); x++) {
char letter = str.charAt(x);
boolean toReplace = false;
for (int j = 0; j < vowels.length; j++) {
if (letter == vowels[j]) {
toReplace = true;
break;
}
}
if (toReplace) {
newStr = newStr + "_";
} else {
newStr = newStr + letter;
}
}

How can i replace a char in a String using chars from another string (Caesar Cypher)(JAVA)

I'm doing a caesar-cypher. Trying to replace all characters from a string to a certain character from the shifted alphabet.
Here is my code so far
public static String caesarify(String str, int key){
String alphabetNormal = shiftAlphabet(0);
String alphabetShifted = shiftAlphabet(key);
for (int i =0; i < str.length();i++){
for (int c =0; c < alphabetNormal.length(); c++) {
if (str.charAt(i) == alphabetNormal.charAt(c)) {
char replacement = alphabetShifted.charAt(c);
str.replace(str.charAt(i), replacement);
}
}
}
return str;
}
public static String shiftAlphabet(int shift) {
int start =0;
if (shift < 0) {
start = (int) 'Z' + shift + 1;
} else {
start = 'A' + shift;
}
String result = "";
char currChar = (char) start;
for(; currChar <= 'Z'; ++currChar) {
result = result + currChar;
}
if(result.length() < 26) {
for(currChar = 'A'; result.length() < 26; ++currChar) {
result = result + currChar;
}
}
return result;
}
I don't know why the string for example "ILIKEDONUTS" doesn't change to "JMJLFEPOVUT" when it's caesarified.
Don't use replace(), or any replace method, to replace a character at a given index in a String. It doesn't work. You're hoping that
str.replace(str.charAt(i), replacement);
will replace the i'th character of str. As pointed out in the other (now deleted) answer, str.replace doesn't change str itself, so you'd need to write
str = str.replace(str.charAt(i), replacement);
But that doesn't work. The replace() method doesn't know what your index i is. It only knows what character to replace. And, as the javadoc for replace() says, it replaces all characters in the string. So suppose that str.charAt(i) is 'a', and you want to replace it with 'd'. This code would replace all a characters with d, including (1) those that you already replaced with a earlier in the loop, so that this will defeat the work you've already done; and (2) a characters that come after this one, which you want to replace with d, but this will fail because later in the loop you will see d and replace it with g.
So you can't use replace(). There are a number of ways to replace the i'th character of a string, including using substring():
str = str.substring(0, i) + replacement + str.substring(i + 1);
But there are better ways, if you are going to replace every character. One is to create a StringBuilder from str, use StringBuilder's setCharAt method to change characters at specified indexes, and then convert the StringBuilder back to a String at the end. You should be able to look at the javadoc to find out what methods to use.
More: After looking into this more, I see why it was returning all A's. This inner loop has an error:
for (int c =0; c < alphabetNormal.length(); c++) {
if (str.charAt(i) == alphabetNormal.charAt(c)) {
char replacement = alphabetShifted.charAt(c);
str.replace(str.charAt(i), replacement);
}
}
Suppose key is 1, and the current character is 'C'. Your inner loop will eventually find C in alphabetNormal; it finds the corresponding character in alphabetShifted, which is D, and replaces C with D.
But then it loops back. Since the next character in alphabetNormal is D, it now matches the new str.char(i), which is now D, and therefore changes it again, to E. Then it loops back, and ... you get the picture.
replace below line
str.replace(str.charAt(i), replacement);
With
str= str.replace(str.charAt(i), replacement);
or you can make a String arr and then replace character in that. in the end create a new string from that array and return.
a better version of caesarify():
public static String caesarify(String str, int key){
String alphabetNormal = shiftAlphabet(0);
String alphabetShifted = shiftAlphabet(key);
//create a char array
char[] arr=str.toCharArray();
//always try to create variable outside of loop
char replacement
for (int i =0; i < arr.length();i++){
for (int c =0; c < alphabetNormal.length(); c++) {
if (arr[i] == alphabetNormal.charAt(c)) {
replacement = alphabetShifted.charAt(c);
//replace char on specific position in the array
arr[i]= replacement;
}
}
}
//return arrray as String
return new String(arr);
}

How to find out if char is number in JAVA, ONLY with string methods?

I need to find out how can I check if a char is a number. The problem is that I can't use any methods except string methods like IndexOf, SubString, length, charAt.
Does anyone have an idea?
If it has to be String methods:
String n = "0123456789";
char c = 'a'; // As I don't know where your char will come from and in what format
int i = n.indexOf(c);
if(i != -1) {
System.out.println("Digit");
} else {
System.out.println("Not digit");
}
But I can't stress enough that this is, well, idiotic and pointless from my point of view.
You can use Character.isDigit() for this.
If you have a string, you can do this :
Character.isDigit(yourString.charAt(index));
And withtout any Character method you can use Regex :
s.substring(startIndex,endIndex).matches("[0-9]")
You can check the character for its UNICODE value:
char c = string.indexOf(...); // or other way to get the character
public static boolean isDigit(char c) {
return c => '0' || c <= '9';
}
You can use the below based on the ASCII values comparison:-
String s = "123456ao";
char[] ss = s.toCharArray();
int intVal = 0;
for( char s1 : ss){
intVal = s1;
if(48 <= intVal && intVal < 58) // checking for ASCII values of numbers
System.out.println(s1+ " is Numeric");
else System.out.println(s1+ " is not Numeric");
}

why my code is not turn out the result that I want?

I want to define a method that input a string then return a string which character in it has been convert
public static String encode(String s){
char[] newArray = {'a','b','c','d','e','f','g','h','i','g','k','l','m'};
char[] newArray2 = {'n','o','p','q','r','s','t','u','v','w','s','y','z'};
for(int i=0; i<s.length();i++){
if(s.charAt(i) == newArray[i]){
s.replace(newArray[i], newArray2[i]);
}
}
return s;
}
public static void main(String[] args){
System.out.println(encode("firefly"));
}
but compiler just return firefly, I know there is a problem in s.charAt(i) == newArray[i] but how to define a method , for example, 'f' this single char to search through out the newArray, instead of if f correspond the first char at newArray? also how to define it when I want uppercase letter switch only with uppercase . then if I input a String like FireFly it will return SverSyl?
Because replace doesn't change the original String. It returns a new String. You need to write
s = s.replace(newArray[i], newArray2[i]);
to assign the modified String back to the variable s.
First, strings in Java are immutable. This mean you can't change them. What you can is create a new one. Second, you compare your string with the translation array to find a match at the same index. It's very difficult to find a match at the same positions and it's not what you want.
You could use the following method:
public static String encode(String s) {
StringBuffer b = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ((c >= 'a' && c <= 'm') || (c >= 'A' && c <= 'M')) {
b.append((char) ((int) c + 13));
continue;
}
if ((c >= 'n' && c <= 'z') || (c >= 'N' && c <= 'Z')) {
b.append((char) ((int) c - 13));
continue;
}
b.append(c);
}
return b.toString();
}
The idea is that you translate each character independently and add it to a string buffer. Then you return the resulting string. To transform a character between 'a' and 'm' you just add 13 to its integer code. To transform a character between 'n' and 'z' you just remove 13 from its integer code. You do the same thing for the capital letters.
When we call this method with "FireFly you were cancelled too soon"
public static void main(String args[]) {
System.out.println(encode("FireFly you were cancelled too soon"));
}
the result is:
SverSyl lbh jrer pnapryyrq gbb fbba
Strings are immutable. So technically you need to create a new object and assign it a reference. You can assign your previous string itself to it:
s = s.replace(newArray[i], newArray2[i]);
At the end of your code you are returning s but it's value has not actually been changed. You need to assign something else to that variable or else you will get the same value you input as the output.

Replacing characters

I have a String entered by the User.
I'm trying to replace all non-uppercase letters(i.e. numbers, or symbols) with spaces without using methods such as replace(), Stringbuilders, or arrays.
This is what I have so far :
public static void formatPlaintext(String sentence){
String sentenceUpper = sentence.toUpperCase();
System.out.println(sentenceUpper);
String emptyString = " ";
for(int i = 0; i< sentenceUpper.length() ; i++){
char ch = sentenceUpper.charAt(i);
if(ch < 'A' || ch > 'Z'){
ch = emptyString.charAt(0);
}
}
}//end of formatPlaintext
I keep getting the error that String index is out of range. I believe it has to do with :
ch = emptyString.charAt(0);
because emptyString doesn't have any characters. But even if I put an arbitrary constant in, it doesn't replace the non-letters with this arbitrary constant.
This isn't how you replace characters in a Java string. In Java, strings are immutable, so you can't set any given index. Additionally, the charAt() method doesn't and can't do anything to the string you're calling it on - all it does is just return the char at that position. Lastly, you probably shouldn't be using void - return the String with characters replaced at the end of the method, then use the return value. You can accomplish this by iterating through your initial string and build a new string, using the static isUpperCase method of the Character class:
public static String formatPlainText(String sentence)
{
String replacedSentence = "";
for(int i = 0; i< sentence.length() ; i++){
char ch = sentence.charAt(i);
if (Character.isUpperCase(ch)) {
replacedSentence += ch;
}
else {
replacedSentence += " ";
}
}
return replacedSentence;
}
If you're going to be using this frequently, or for particularly long Strings, you should absolutely use a StringBuilder instead - concatenating String on a character-by-character basis is deeply inefficient.
You have to remember that arguments in Java are passed as values, not as references, and in this case the String is an immutable object, i.e. an String cannot be changed, when you do a concatenation or replace you're effectively creating a new String.
What I would recommend is to modify your code a little bit to return the new String that was built.
public static String formatPlaintext(String sentence){
String sentenceUpper = sentence.toUpperCase();
System.out.println(sentenceUpper);
StringBuilder builder = new StringBuilder;
for(int i = 0; i< sentenceUpper.length() ; i++){
char ch = sentenceUpper.charAt(i);
if(ch < 'A' || ch > 'Z'){
builder.append(' ');
} else {
builder.append(ch);
}
}
return builder.toString();
}

Categories

Resources