How to convert a string to uppercase without using the toUpperCase method? - java

I'm a beginner at java and can't get this code to work. What I have to do is convert any inputted string to uppercase without using the toUpperCase string method. This is what I have:
public String toUpperCase(String str)
{
for(int i = 0; i < str.length(); i++)
{
char a = str.charAt(i);
a = Character.toUpperCase(a);
str += Character.toString(a);
}
return str;
}

You are using str as input, and output (so your String has infinite length, as you keep adding characters). And you can use static, because you aren't using instance state. And, you might use a for-each loop. Finally, add another String, or better a StringBuilder like
public static String toUpperCase(String str) {
StringBuilder sb = new StringBuilder();
for (char ch : str.toCharArray()) {
sb.append(Character.toUpperCase(ch));
}
return sb.toString();
}

There is the following way, but it doesn't consider any characters outside of English (no diacritics, no other languageā€™s characters behind a-z).
public String toUpperCase(String str) {
char[] chars = str.toCharArray();
for (int i=0; i<chars.length; i++) {
char c = chars[i];
if ('a' <= c && c <= 'z') {
chars[i] = (char) (c - 'a' + 'A');
}
}
return new String(chars);
}

I am aware your school probably do not allow you to use StringBuilder and in case you can't use array as well. This is another primitive approach which your school may accept:
public static String toUpperCase(String s){
String str = "";
for(int x=0; x<s.length(); x++){
char ch = s.charAt(x);
if(ch >= 'a' && ch <= 'z')
str += "" + (char)(ch - 32);
else
str += "" + ch;
}
return str;
}
Test:
System.out.println(toUpperCase("aAbBcC"));
Output:
AABBCC

Since you can't use the toUpperCase() method, you can use the ASCII table to get from a lower case letter to an upper case letter by subtracting 32.
'a' = 97, 'A' = 65
'b' = 98, 'B' = 66
...
'z' = 122, 'Z' = 90
public static int DIFF = 'a' - 'A'; // 32
public static String toUpperCase(String str) {
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray()) {
if (Character.isLowerCase(c)) {
sb.append(String.valueOf((char)(c - DIFF)));
} else {
sb.append(c);
}
}
return sb.toString();
}

try it:
public static String toUpperCase(String str) {
String result = "";
for (int i = 0; i < str.length(); i++) {
int v = str.charAt(i);
if (v > 96 && v < 123) {
v -= 32;
}
result+=(char)v;
}
return result;
}

C'mon guys, Java 8 has been out for years!
/**
* Converts an all-lowercase String to
* uppercase. Retains only spaces, any
* other characters will be lost.
*/
public static String toUpperCase(String s) {
int diff = 'a' - 'A'; // 32
return s.chars()
.filter(c -> c >= 'a' && c <= 'z' || c == ' ')
.mapToObj(c -> String.valueOf((char) (c - (diff))))
.collect(Collectors.joining());
}

Related

How do I replace one character occurrence in a string?

How would I replace a string like "Hello" with "Helko", only replacing the second L but not the first?
Use replaceAll with regular expression:
System.out.println("Hello".replaceAll("((?!^).*?|[^l]*l.*?)l","$1k"));
Simple Approach (based on excluding the second l):
Search for first index of l using indexOf and do another search for l but this time start searching from firstL + 1 which will lead to the second index l if exist!
Do a test if there is second l, If So Exclude the second l by using substring which take only the first part (start from zero till secondL) and second part (start from secondL+1 till the end), Concatenate them with k.
public static String removeSecondL(String str) {
int firstL = str.indexOf('l');
int secondL = str.indexOf('l', firstL+1);
if(secondL != -1) {
String firstPart = str.substring(0, secondL);
String secondPart = str.substring(secondL + 1);
return firstPart + 'k' + secondPart;
}
return str;
}
Tests:
public static void main(String[] args) {
System.out.println(removeSecondL("Hello")); // Helko
System.out.println(removeSecondL("lololo")); // lokolo
System.out.println(removeSecondL("no l")); // no l
}
Another Approach: Convert the String into a char array, and declare a variable lFound gonna look for the first occurrence of letter l, if it found next l will be converted to k and exit the loop by break.
String str = "Hello";
char[] chars = str.toCharArray();
boolean lFound = false;
for (int i = 0; i < chars.length; i++) {
if(lFound) {
if(chars[i] == 'l')
{
chars[i] = 'K';
break;
}
}else {
lFound = chars[i] == 'l'; //if(chars[i] == 'l') lFound = true;
}
}
System.out.println(chars); //HelKo
Lately, I turned to the conversation and I saw you writing:
I wanted to replace one instance of a character with another, like "aaaaa" with "aabaa", where only the third 'a' is replaced with 'b', but not the others.
Just follow second approach I posted with additional tests.
public static char[] removeSpecificChar(String str, char a, char b, int position) {
char[] chars = str.toCharArray();
int pos = 1;
for (int i = 0; i < chars.length; i++) {
if(pos == position) {
if(chars[i] == a)
{
chars[i] = b;
break;
}
}else {
pos += (chars[i] == a) ? 1 : 0;
}
}
return chars;
}
Test:
String str = "aaaaa";
System.out.println(removeSpecificChar(str, 'a', 'b', 3));
Print:
aabaa

Add delimiter if String contains a character?

I'm trying to figure out how to use a loop to append the delimiter ":" before the String s is found to contain a letter A-F.
If I have s = "10584f" then I would want the output to be "10584:f"
How should I go about doing this?
This is a simple solution that checks if it contains letters between a to f and put `:' accordingly.
public static void main(String[] args) {
String s = "10584f";
String newString = "";
for(int i=0;i<s.length();i++) {
if((int)s.charAt(i)>= (int)'a' && (int)s.charAt(i)<= (int)'f') {
newString = newString + ":" + s.charAt(i);
}else {
newString = newString + s.charAt(i);
}
}
System.out.println(newString);
}
You need to check for the ASCII code of each character and append the delimiter before it on this condition:
public class Main {
public static void main(String[] args) {
String s = "10584f";
System.out.println(appendDelimiter(s));
}
private static String appendDelimiter(String s) {
StringBuilder sb = new StringBuilder();
for(char c : s.toCharArray()) {
int charCode = (int) c;
if((charCode >= 65 && charCode <= 70) || (charCode >= 97 && charCode <= 102))
sb.append(":");
sb.append(c);
}
return sb.toString();
}
}
Output:
10584:f
If your target string consists of digits followed by a single letter from A-F or a-f, a simple solution can be: replacement of the regex-match, (\\d+)([A-Fa-f]). This regex means group(1) consisting of digits and group(2) consisting of a letter from A-F or a-f. The regex can be replaced with $1:$2 where $1 and $2 specify group(1) and group(2) respectively.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Test strings
String[] arr = { "10584f", "12345A", "13456b", "23456F" };
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i].replaceAll("(\\d+)([A-Fa-f])", "$1:$2");
}
// After replacement
System.out.println(Arrays.toString(arr));
}
}
Output:
[10584:f, 12345:A, 13456:b, 23456:F]
However, if the string can have multiple letters followed by digits and you want each letter to be prepended with a :, you can iterate the string starting from the index, 1 until the last character of the string and if you come across a letter, prepend it with a : as done in the function, withColonBeforeLetters given below:
Demo:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Test strings
String[] arr = { "10584f", "12345A", "13456b", "23456F", "1abc", "123aBc" };
for (int i = 0; i < arr.length; i++) {
arr[i] = withColonBeforeLetters(arr[i]);
}
// After replacement
System.out.println(Arrays.toString(arr));
}
static String withColonBeforeLetters(String s) {
StringBuilder sb = new StringBuilder();
// Put the first letter into sb
sb.append(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
char ch = s.charAt(i);
if ((ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f')) {
sb.append(':').append(ch);
} else {
sb.append(ch);
}
}
return sb.toString();
}
}
Output:
[10584:f, 12345:A, 13456:b, 23456:F, 1:a:b:c, 123:a:B:c]

How to get upper case instead of lower case in a string without method toUppercase. P.S below

How to get upper case instead of lower case in a string without method toUppercase, but the other symbols should not change in the string
package com.telukhin.hw6;
public class Task1 {
public static void main(String[] args) {
} private static String lowerCase(String s) {
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if(ch >= 'a' && ch < 'z') {
ch = ch - '32';
}
}
}
}
You can do it as follows:
public class Task1 {
public static void main(String[] args) {
System.out.println(lowerCase("HELLO"));
}
private static String lowerCase(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch >= 65 && ch <= 90)
sb.append((char)(ch+32));
else
sb.append((char)ch);
}
return sb.toString();
}
}
Output:
hello
Please check https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html for reference.
UPDATE: Adding a method to convert a String to upper case as well
public class Task1 {
public static void main(String[] args) {
System.out.println(lowerCase("HELLO"));
System.out.println(upperCase("hello"));
}
private static String lowerCase(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch >= 65 && ch <= 90) //ASCII value of 'A'is 65 and that of 'Z' is 90
sb.append((char)(ch+32));
else
sb.append((char)ch);
}
return sb.toString();
}
private static String upperCase(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch >= 97 && ch <= 122) //ASCII value of 'a'is 97 and that of 'z' is 122
sb.append((char)(ch-32));
else
sb.append((char)ch);
}
return sb.toString();
}
}
Output:
hello
HELLO
ASCII value of lowercase char a to z ranges from 97 to 122
ASCII value of uppercase char A to Z ranges from 65 to 92
For conversion we are adding 32 from the ASCII value of input char.
Add this in your if statement:
ch = ch + 32;
Assuming this isn't homework, which the limit of not using toUppercase sort of implies, you could do this:
public class Main
{
public static void main(String[] argv)
{
final String upper = toUpperCase("HELLO1234#world.CoM");
System.out.println(upper);
}
private static String toUpperCase(final String s)
{
final StringBuilder builder = new StringBuilder();
for(final char c : s.toCharArray())
{
final char upper = Character.toUpperCase(c);
builder.append(upper);
}
return builder.toString();
}
}
This will handle non-ascii characters. Alternatively, you can still use the 65 and 90 bit in place of Character.toUpperCase
One more example. This converts the string to an array of characters for working with, and then creates a new string with the result. It seems more convenient than using charAt, StringBuilder, etc.
Like many of the other answers, valid only for the 26 letters that also occur in ASCII.
class Foo {
public static String upcase(String str) {
char[] arr = str.toCharArray();
for (int k=0; k<arr.length; k++) {
if (arr[k] >= 'a' && arr[k] <= 'z') {
arr[k] -= ('a'-'A');
}
}
return new String(arr);
}
public static void main(String... args) {
String test = "a9z A?Z";
System.out.println(test + " ==> " + upcase(test));
}
}

Implement Hyphen Between Each Digit in Output

So I'm writing a program that mimics a phone keypad, whereas it would convert a string of text to integers: abc(2), def(3), ghi(4), jkl(5), mno(6), pqrs(7), tuv(8), wxyz(9). Except the output should have hyphens(-) between the digits.
Example input: Alabama
Output: 2-5-2-2-2-6-2
But my code only outputs 2522262. How would I go about formatting this correctly?
import java.util.Scanner;
public class PhoneKeypad {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(getNumbers(str));
}
private static final char[] DIGITS = (
// ABC DEF
"222" + "333"
+ // GHI JKL MNO
"444" + "555" + "666"
+ // PQRS TUV WXYZ
"7777" + "888" + "9999").toCharArray();
public static String getNumbers(CharSequence s) {
StringBuilder result = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
char c = Character.toUpperCase(s.charAt(i));
if ('A' <= c && c <= 'Z') {
result.append(DIGITS[c - 'A']);
}
}
}
Add the - after each digit. Easiest way I see, change
result.append(DIGITS[c - 'A']);
to
result.append(DIGITS[c - 'A']).append('-');
Then remove the last - when you return like,
public static String getNumbers(CharSequence s) {
StringBuilder result = new StringBuilder(s.length() * 2); // <-- digit-digit...
for (int i = 0; i < s.length(); i++) {
char c = Character.toUpperCase(s.charAt(i));
if ('A' <= c && c <= 'Z') {
result.append(DIGITS[c - 'A']).append('-');
}
}
if (result.length() > 1) {
result.setLength(result.length() - 1);
}
return result.toString(); // <-- Don't forget to return the result.
}
You might find it easier if you pass in s, you could call toUpperCase() and toCharArray() and then use a for-each loop. Like,
public static String getNumbers(String s) {
StringBuilder result = new StringBuilder(s.length() * 2);
for (char c : s.toUpperCase().toCharArray()) {
if (c >= 'A' && c <= 'Z') { // <-- I find this test easier to read,
// but that's just my opinion.
result.append(DIGITS[c - 'A']).append('-');
}
}
if (result.length() > 1) {
result.setLength(result.length() - 1);
}
return result.toString();
}

Java Letter changes arraylist to string without commas but including white spaces

Trying to complete this challenge from coderbyte: "Using the Java language, have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string."
The problem that i am having is the replace is pulling on the white spaces between characters, but I need it to preserve white spaces between words. Is there a better solution to this?
import java.util.Arrays;
import java.util.Scanner;
public class nextLetter {
public static String LetterChanges(String str) {
String[] inputString = str.replaceAll("[^a-zA-Z ]", "").split("");
String[] alph= "abcdefghijklmnopqrstuvwxyz".split("");
String[] vowel ="aeiouy".split("");
for(int i=0; i<inputString.length; i++){
int index= Arrays.asList(alph).indexOf(inputString[i])+1;
inputString[i]= alph[index];
if(Arrays.asList(vowel).indexOf(inputString[i])>0){
inputString[i]= inputString[i].toUpperCase();
}
}
//System.out.println(Arrays.toString(inputString));
return Arrays.toString(inputString)
.replace(" ","")
.replace(",", "") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "")//remove the left bracket
.replace(" ","")
.trim();
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter a sentence");
System.out.print(LetterChanges(s.nextLine()));
}
}
Also I would not mind any pointers on how to improve this!
Note: I've changed the method name to something a bit more descriptive. The method assumes that you're only working with lowercase letters.
public static void main(String[] args){
System.out.println(shiftLetters("abcdz")); //bcdea
}
public static String shiftLetters(String str){
StringBuilder shiftedWord = new StringBuilder();
for (int i = 0; i < str.length(); i++){
char currentChar = str.charAt(i);
if (currentChar != ' '){
currentChar += 1;
if (currentChar > 'z'){
currentChar = 'a';
}
}
shiftedWord.append(currentChar);
}
return shiftedWord.toString();
}
This is the general logic flow of this program: create a cumulative StringBuilder object that will eventually be the return value of the method. Loop through all characters in the string; if the character is a whitespace character, then simply don't bother with it and add it onto the StringBuilder as is. Else, add one to the current character. Note that chars are an integral(4.2.1) primitive type, so you may add ints to a char as such. If it's the special case that the new char is out of the normal a-z range, set it back to a.
Taking Use of Java 8's API
public static String functionalShiftLetters(String str){
return str
.chars()
.map(c -> c != ' ' ? c + 1 : c)
.map(c -> c > 'z'? 'a' : c)
.collect(StringBuilder::new,
StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
}
This preserves all other characters and handles the vowels.
public static String LetterChanges(String str)
{
str = str.toLowerCase();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
if ('a' <= c && c <= 'z')
{
c = (c == 'z') ? 'a' : (char) (c + 1);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
c = Character.toUpperCase(c);
}
}
sb.append(c);
}
return sb.toString();
}
Input: abcdefghijklmnopqrstuvwxyz 1234567890
Output: bcdEfghIjklmnOpqrstUvwxyzA 1234567890
If have fixed alphabeth and swapping algorithm you can use a static dictionary.
public static HashMap<String,String> dictionary = new HashMap<>();
static{
dictionary.put(" ", " ");
dictionary.put("a", "b");
dictionary.put("b", "c");
dictionary.put("c", "d");
dictionary.put("d", "E");
.
.
dictionary.put("z", "A");
}
public static String shiftLetters(String str){
StringBuffer response = new StringBuffer();
for (int i = 0; i < str.length(); i++){
response.append(dictionary.get(String.valueOf(str.charAt(i))));
}
return response.toString();
}

Categories

Resources