The Java char primitive type is a 16 bit representation of a single character.
Multiple chars can comprise a string, such as "word", or chars can be processed independently.
A char literal is surrounded by single quotes (e.g. 'A').
char lowerA = 'a';
char upperB = 'B';
chars of a String
The String.toCharArray method returns a String's chars as an array.
As mentioned in arrays, you can use a for loop to iterate over the array.
String text = "Hello";
char[] asArray = text.toCharArray();
for (char ch: asArray) {
System.out.println(ch);
}
// Outputs:
// H
// e
// l
// l
// o
There are many builtin library methods to inspect and manipulate chars.
These can be found as static methods of the java.lang.Character class.
Here are some examples:
Character.isWhitespace(' '); // true
Character.isWhitespace('#'); // false
Character.isLetter('a'); // true
Character.isLetter('3'); // false
Character.isDigit('6'); // true
Character.isDigit('?'); // false
char to a String
The + operator can be used to add a char to a String.
'a' + " banana" // => "a banana"
"banana " + 'a' // => "banana a"
Becareful not to use + to join two chars together to form a String!
Adding two chars this way gives an int, not a String!
For example:
'b' + 'c';
// => 197 (not the String "bc")
This is because Java promotes the char to an int (see 4.2 Primitive Types and Values of the Java Language Specification).
However, when there are many characters to be added, it can be more efficient to use a StringBuilder instead:
StringBuilder builder = new StringBuilder();
builder.append('a');
builder.append('b');
builder.append('c');
String builtString = builder.toString();
// => abc
In this exercise you will implement a partial set of utility routines to help a developer clean up SqueakyClean names.
In the 4 tasks you will gradually build up the clean method.
A valid SqueakyClean name is comprised of zero or more letters and underscores.
In all cases the input string is guaranteed to be non-null. Note that the clean method should treat an empty string as valid.
Implement the (static) SqueakyClean.clean() method to replace any spaces with underscores. This also applies to leading and trailing spaces.
SqueakyClean.clean("my Id");
// => "my___Id"
Modify the (static) SqueakyClean.clean() method to convert kebab-case to camelCase.
SqueakyClean.clean("a-bc");
// => "aBc"
Modify the (static) SqueakyClean.clean() method to convert leetspeak to normal text.
For simplicity we will only be replacing 4, 3, 0, 1 and 7 with a, e, o, l, and t, respectively.
SqueakyClean.clean("H3ll0 W0rld");
// => "Hello_World"
SqueakyClean.clean("4 73s7");
// => "a_test"
Modify the (static) SqueakyClean.clean() method to omit any characters that are not letters.
SqueakyClean.clean("a$#.b");
// => "ab"
Sign up to Exercism to learn and master Java with 26 concepts158 exercises, and real human mentoring, all for free.