Is there any other way to remove all whitespaces in a string? - java

I have a programming homework. It says that I need to reverse the string first, then change it to uppercase and then remove all the whitespaces. I actually did it, but our professor didn't say anything about using replaceAll() method. Is there any other way to do it beside replaceAll()?
Here is my code:
public static void main(String[] args) {
String line = "the quick brown fox";
String reverse = "";
for (int i = line.length() - 1; i >= 0; i--) {
reverse = reverse + line.charAt(i);
}
System.out.println(reverse.toUpperCase().replaceAll("\\s", ""));
}

You can check each character in turn using Character.isWhitespace. Additionally, it is generally better to use a StringBuilder when concatenating inside a loop.
public static void main(String[] args) {
String line = "the quick brown fox";
StringBuilder sb = new StringBuilder(line.length());
for (int i = line.length() - 1; i >= 0; i--) {
char c = line.charAt(i);
if(!Character.isWhitespace(c)) sb.append(Character.toUpperCase(c));
}
System.out.println(sb);
}

#Khelwood's answer as code:
public static void main(String[] args) {
String line = "the quick brown fox";
String reverse = "";
for (int i = line.length() - 1; i >= 0; i--) {
char currentChar = line.charAt(i);
if (currentChar != ' ') {
reverse += currentChar;
}
}
System.out.println(reverse.toUpperCase());
}

Character#isWhitespace
Initialize a StringBuilder object and iterate through each character of the uppercased string. While iterating, use Character#isWhitespace to check if the character is a whitespace character. If not, append the character to the StringBuilder object. After the loop is finished, the StringBuilder object will have all characters except the whitespace characters.
public class Main {
public static void main(String[] args) {
String line = "the quick brown fox";
String reverse = "";
for (int i = line.length() - 1; i >= 0; i--) {
reverse = reverse + line.charAt(i);
}
String upperCased = reverse.toUpperCase();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < upperCased.length(); i++) {
char ch = upperCased.charAt(i);
if (!Character.isWhitespace(ch)) {
sb.append(ch);
}
}
System.out.println("The given string: " + line);
System.out.println("The reverse of the given string: " + reverse);
System.out.println("The reverse of the given string in UPPER case: " + upperCased);
System.out.println("After removing all space from the reverse of the given string in UPPER case: " + sb);
}
}
Output:
The given string: the quick brown fox
The reverse of the given string: xof nworb kciuq eht
The reverse of the given string in UPPER case: XOF NWORB KCIUQ EHT
After removing all space from the reverse of the given string in UPPER case: XOFNWORBKCIUQEHT
Note:
If you want to convert sb to a String, use sb.toString().
You can use String instead of StringBuilder but I recommend you use StringBuilder instead of String for such a case because repeated string concatenation in a loop creates additional as many instances of String as the number of concatenation. Check this discussion to learn more about it.

to strictly follow the professors description (and intentions?):
public static void main(String[] args) {
String line = "the quick brown fox";
String reverse = "";
for (int i = line.length() - 1; i >= 0; i--) {
reverse = reverse + line.charAt(i);
}
String upperCase = reverse.toUpperCase();
String noSpaces = "";
for (int i = 0; i < upperCase.length(); i++) {
char ch = upperCase.charAt(i);
if (!Character.isWhitespace(ch)) {
noSpaces = noSpaces + ch; // or noSpaces += ch;
}
}
System.out.println(noSpaces);
}
Note 1: this can all be done with one loop, but that would not match the description (or no (user)loop at all?).
Note 2: the use of StringBuilder is not needed anymore (when using an actual Java version (>= 11)) - actually I believe it is more efficient not to use it, the compiler does better job (see StringConcatFactory)
Note 3: if allowed to use StringBuilder, it also has a reverse method
Note 4: be aware (for future) that replaceAll() works with regular expression, very powerful, but kind of overkill to just replace a char - replace() would be more moderate

Even without using replaceAll() it’s still a one-liner:
String reverse =
new StringBuilder(line)
.reverse()
.toString()
.toUpperCase()
.replace(" ", "");

Here are two ways. The first uses a standard loop.
String line = "the quick brown fox";
StringBuilder sb = new StringBuilder();
for (int i = line.length() - 1; i >= 0; i--) {
char ch;
if ((ch = line.charAt(i)) != ' ') {
sb.append(Character.toUpperCase(ch));
}
}
System.out.println(sb.toString());
Prints
XOFNWORBKCIUQEHT
The second makes use of StringBuilder and replaceAll. And regardless, you should ask your professor since nothing was overtly forbidden.
String str = new StringBuilder("the quick brown fox")
.reverse().toString().replaceAll("\\s+", "").toUpperCase();
System.out.println(str);
Also prints
XOFNWORBKCIUQEHT

You can use String.codePoints method to iterate over int values of the characters of this string, to reverse their order, change to uppercase and remove whitespaces:
String line = "the quick brown fox";
String reverse = line
// return IntStream
.codePoints()
// return Stream<Character>
.mapToObj(ch -> (char) ch)
// reverse the order
// of characters once
.sorted((ch1, ch2) -> -1)
// change to uppercase
.map(Character::toUpperCase)
// remove whitespaces
.filter(ch -> !Character.isWhitespace(ch))
// return Stream<String>
.map(String::valueOf)
// join strings with
// characters back
// to a single string
.collect(Collectors.joining());
System.out.println(reverse); // XOFNWORBKCIUQEHT
See also: Is there a way to reverse specific arrays in a multidimensional array?

If you do not need to store the reversed line, you can also just iterate it backwards and print the character immediately.
public static void main(String[] args) {
String line = "the quick brown fox";
for (char c : line.toUpperCase().toCharArray()) {
if (!Character.isWhitespace(c)) {
System.out.print(c);
}
}
}

You can iterate over character indices in reverse order, convert them to uppercase and remove spaces as follows:
String str = "the quick brown fox";
String reverse = IntStream
// iterate over characters in reverse order
.iterate(str.length() - 1, i -> i >= 0, i -> i - 1)
// take a character by its index
.mapToObj(str::charAt)
// filter only letters
.filter(Character::isLetter)
// character to uppercase
.map(Character::toUpperCase)
// Stream<String>
.map(String::valueOf)
// concatenate into one line
.collect(Collectors.joining());
// output
System.out.println(reverse); // XOFNWORBKCIUQEHT

If the sequence of actions does not matter, then you can first change this string to uppercase, then stream over the character codepoins and filter out whitespaces, and then concatenate back the remaining characters in reverse order:
String line = "the quick brown fox";
String reverse = line
// upper case String
.toUpperCase()
// IntStream over the character code points
.codePoints()
// filter out the space characters
.filter(ch -> !Character.isSpaceChar(ch))
// Stream<String>
.mapToObj(Character::toString)
// concatenate characters in reverse order
.reduce((a, b) -> b + a)
.orElse(null);
System.out.println(reverse); // XOFNWORBKCIUQEHT

Related

How to write a Java program to include whitespaces at the beginning of a string that we want to reverse?

I want to reverse a string.
input: Computer;
This input contains 4 whitespaces in the beginning of the word 'computer'.I want to include these 4 whitespaces in the beginning of the reversed string also.So,the program should include all the whitespaces I put at the beginning while taking the reverse too(I put 4 whitespaces as an example only).
output:" retupmoc";
I am attaching my code here.
package BasicTesting;
import java.util.*;
public class Corrected_StringRev {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter a string: ");
String str= sc.nextLine();
String reversed = reverseString( str );
System.out.println( reversed );
}
public static String reverseString( String newString ) {
char ch[]=newString.toCharArray();
String rev="";
for(int i=ch.length-1;i>=0;i--){
rev+=ch[i];
}
return rev;
}
}
How can I change this code to include the above requirement.Please,rewrite the code.Hope ypu will help.Thanks in adavance!
The logic is simple:
Traverse the start of the string and add whitespaces to rev until you meet the first non-whitespace
Do your string reversal and stop before the whitespace section begins
public static String reverseString(String newString) {
char ch[] = newString.toCharArray();
String rev = "";
int nWhitespace;
for (nWhitespace = 0; nWhitespace < ch.length; nWhitespace++) {
if (!Character.isWhitespace(ch[i]) {
break;
}
rev += ch[i];
}
for(int i = ch.length - 1; i >= nWhitespace; i--){
rev += ch[i];
}
return rev;
}
By the way, you can improve your code by using StringBuilder instead of +=.
Here instead of keeping a count and then adding it, we will be checking if the character we are at currently in the string is a whitespace character. If yes, we add a space to our string builder.
As soon as we come across a non-whitespace character, we break out of the loop.
strB.append(new StringBuilder(inputString.trim()).reverse().toString());
return strB.toString();
What this code does is:
Take string inputString and trim it (remove trailing and leading whitespaces.
Creates a new (anonymous) object of a StringBuilder and reverses it.
Convert it into a string to append it to our original StringBuilder strB after the whitespaces.
Finally, we convert it into String and return it.
Some tips:
I will be using StringBuilder as it is mutable so saves space and also it contains a function to reverse it directly.
You should not call the length function of string in the loop as it will call it for every loop. Better to store the value in a variable and use that variable in the loop.
public static String reverseString(String inputString) {
StringBuilder strB = new StringBuilder();
int len = inputString.length();
for (int i = 0; i<len && inputString.charAt(i) == ' '; i++) {
strB.append(" ");
}
strB.append(new StringBuilder(inputString.trim()).reverse().toString());
return strB.toString();
}

How to convert given string in comma seperated characters in java?

public class StringDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
String name = "String";
char[] c = name.toCharArray();
for (char ch : c) {
System.out.print(ch);
System.out.print(",");
}
}
}
This gives me output as
S,t,r,i,n,g,
I don't want that last comma, how to get output as S,t,r,i,n,g
You can also do it on a higher level without writing your own loop. It's not faster or anything, but the code is more clear about what it's doing: "Split my string into characters and join it back together, separated by commas!" ...
String name = "String";
String separated = String.join(",", name.split(""));
System.out.println(separated);
EDIT: String.join() is available from Java 1.8 and up.
I would personally use a StringBuilder for this task.
What you need, is to apply some logic that can distinguish whether or not a comma is needed. You loop through the characters just like you did and you always append a comma before the next character, except on the first iteration.
Example:
public static void main(String[] args) {
String test = "String";
StringBuilder sb = new StringBuilder();
for (char ch : test.toCharArray()) {
if (sb.length() != 0) {
sb.append(",");
}
sb.append(ch);
}
System.out.println(sb.toString());
}
Output:
S,t,r,i,n,g
Another way without StringBuilder and using just a traditional for loop, but using the same logic:
public static void main(String[] args) {
String test = "String";
char[] chars = test.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (i != 0) {
System.out.print(",");
}
System.out.print(chars[i]);
}
}
Output:
S,t,r,i,n,g
Sure, but for this you need a for loop based on the length of c, other solutions are not as straight IMHO:
String name="String";
char[] c = name.toCharArray();
for (int i = 0; i < c.length; i++){
char ch = c[i];
System.out.print(ch);
if( i != c.length -1 ){
System.out.print(",");
}
}
Some additional 2 Cents:
You can stream the character int values, map them to a List<String> where each element is a single char as String and finally use String.join(..., ...) in order to get the desired result, a comma separated String of all the characters in the original String:
public static void main(String[] args) {
// take an example String
String name = "Stringchars";
// make a list of characters as String of it by streaming the chars
List<String> nameCharsAsString = name.chars()
// mapping each one to a String
.mapToObj(e -> String.valueOf((char) e))
// and collect them in a list
.collect(Collectors.toList());
// then join the elements of that list to a comma separated String
String nameCharsCommaSeparated = String.join(",", nameCharsAsString);
// and print it
System.out.println(nameCharsCommaSeparated);
}
Running this code results in the following output:
S,t,r,i,n,g,c,h,a,r,s
This is just another possibility of getting your desired result, it is not necessarily the best solution.
You can use Stream to do that. Please check below,
String result = Arrays.stream(name.split("")).collect(Collectors.joining(","));
Output:
S,t,r,i,n,g

Java - Make character after space uppercase?

I'm trying to have the letter after every space turn uppercase. Can someone tell me what's wrong with the following method? Given phrase "this is a test" it returns "ThIs Is A TesT" instead of "this Is A Test"
public String toTitleCase(String phrase) {
for (int i=0; i<phrase.length(); i++) {
if(phrase.substring(i,i+1).equals(" ")) {
phrase = phrase.replace(phrase.substring(i+1,i+2),phrase.substring(i+1,i+2).toUpperCase());
}
}
return phrase;
}
The problem in your code is that String.replace replaces each target character present in the String, and not only the one you want.
You could work directly on an array of chars instead of on the String:
public static String toTitleCase(String phrase) {
// convert the string to an array
char[] phraseChars = phrase.toCharArray();
for (int i = 0; i < phraseChars.length - 1; i++) {
if(phraseChars[i] == ' ') {
phraseChars[i+1] = Character.toUpperCase(phraseChars[i+1]);
}
}
// convert the array to string
return String.valueOf(phraseChars);
}
It's replacing all t, try below code.
It will help you.
String phrase="this is a test";
for (int i=0; i<phrase.length(); i++) {
if(phrase.substring(i,i+1).equals(" ")) {
System.out.println(phrase.substring(i+1,i+2));
phrase = phrase.replace(phrase.substring(i,i+2),phrase.substring(i,i+2).toUpperCase());
}
}
System.out.println(phrase);
Use streams (or split) to split your string into parts, don't do it manually using substring.
Try below code
String test = "this is a test";
UnaryOperator<String> capitalize = str ->
str.substring(0,1).toUpperCase() + str.substring(1).toLowerCase();
String result =
Stream.of(
test.split(" ")
).map(capitalize)
.collect(
Collectors.joining(" ")
);
System.out.println(result);
Output: This Is A Test
When you replace a substring it will replace the each occurrence of that substring - which is not necessarily the one you are trying to replace. This is why it is replacing letters inside words.
Switching to a StringBuilder here to poke individual characters. Note that we don't traverse the entire String because there is no next-character to capitalize at the last character.
public String toTitleCase(String phrase) {
StringBuilder sb = new StringBuilder(phrase);
for (int index = 0 ; index < phrase.length - 1 ; ++index) {
if (sb.charAt(index) == ' ') {
sb.setCharAt(index + 1, Character.toUppercase(sb.charAt(index + 1)));
}
}
return sb.toString();
}
If a letter is first in any word, it will be replaced everywhere. In your case, all t,i and a will be uppercase.
Taking example for is. It is find a space before. Than in if body, what actually happen:
phrase = phrase.replace("i","I");
And all i are replaced with I.
String class cannot replace at a specific position.
You have to options:
using StringBuilder which can replace at a specific position.
String toTitleCase(String phrase) {
StringBuilder sb= new StringBuilder(phrase);
for (int i=0; i<phrase.length(); i++) {
if(i==0 || phrase.charAt(i-1)==' ') {
sb.replace(i,i+1,phrase.substring(i,i+1).toUpperCase());
}
}
return sb.toString();
}
or with stream, which is the method I prefer because is one-line. This way you don't preserve white-spaces( multiple consecutive white-spaces will be replaced with only one space), but usually you want this.
Arrays.asList(phrase.split("\\s+")).stream().map(x->x.substring(0,1).toUpperCase()+x.substring(1)).collect(Collectors.joining(" "));

How can I get the whole String printed out and not only the single character?

Here is my problem: I'm building a StringBuilder and I built a toLowerCase() method which only gives me back a single character and not the whole string.
public MyStringBuilder1 toLowerCase() {
String newStr = "";
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') {
newStr = newStr + (char)(s.charAt(i) + 32) + "";
}
}
return new MyStringBuilder1(newStr);
}
public static void main(String[] args) {
// Create a MyStringBuilder1 object
MyStringBuilder1 str1 = new MyStringBuilder1("Radixsort");
// Display string as lowercase
System.out.println("\nString to lower case: " + str1.toLowerCase());
}
you can use toString() on StringBuilder in order to return String
but you aren't leveraging the StringBuilder power, when it come to long strings the concatenation of them might take great amount of resources
in order to concatenate strings, one string is copied to a new slot in the memory and then the next one
StringBuilder gives an List like behaviour, you can append char dynamically to the stringBuilder with much less effort
so instead of
newStr = newStr + (char)(s.charAt(i) + 32) + "";
you better use
stringBuilder.append((char)(s.charAt(i) + 32))
suggest to read the following tutorial
keep in mind, the significant performance gain will increase with the string length, but on short strings, the compiler optimization will yield much better performance

How to check if a string contains all the letters of the alphabet? [duplicate]

This question already has answers here:
Check if string has all the letters of the alphabet
(15 answers)
Closed 6 years ago.
I am trying to check if a string contains all the letters of the alphabet. I created an ArrayList which contains the whole alphabet. I converted the string to char array and I'm iterating through the character array, and for every character present in the ArrayList I'm removing an element from it. And in the end, I'm trying to check if the Arraylist is empty to see if all elements have been removed. That would indicate the string contains all the letters of the alphabet.
Unfortunately, the code is throwing IndexOutOfBoundsException error inside the if condition where I'm removing elements from the arraylist
List<Character> alphabets = new ArrayList<Character>();
alphabets.add('a');
alphabets.add('b');
alphabets.add('c');
alphabets.add('d');
alphabets.add('e');
alphabets.add('f');
alphabets.add('g');
alphabets.add('h');
alphabets.add('i');
alphabets.add('j');
alphabets.add('k');
alphabets.add('l');
alphabets.add('m');
alphabets.add('n');
alphabets.add('o');
alphabets.add('p');
alphabets.add('q');
alphabets.add('r');
alphabets.add('s');
alphabets.add('t');
alphabets.add('u');
alphabets.add('v');
alphabets.add('w');
alphabets.add('x');
alphabets.add('y');
alphabets.add('z');
// This is the string- I've just put a random example
String str = "a dog is running crazily on the ground who doesn't care about the world";
//Remove all the spaces
str = str.replace(" ", "");
// Convert the string to character array
char[] strChar = str.toCharArray();
for (int i = 0; i < strChar.length; i++) {
char inp = strChar[i];
if (alphabets.contains(inp)) {
alphabets.remove(inp);
}
}
if (alphabets.isEmpty())
System.out.println("String contains all alphabets");
else
System.out.println("String DOESN'T contains all alphabets");
All these solutions seem to do a lot of work for a relatively simple check, especially given Java 8's stream API:
/* Your lowercase string */.chars()
.filter(i -> i >= 'a' && i <= 'z')
.distinct().count() == 26;
Edit: For speed
If you want to end the string iteration as soon as the entire alphabet is found while still using streams, then you can keep track with a HashSet internally:
Set<Integer> chars = new HashSet<>();
String s = /* Your lowercase string */;
s.length() > 25 && s.chars()
.filter(i -> i >= 'a' && i <= 'z') //only alphabet
.filter(chars::add) //add to our tracking set if we reach this point
.filter(i -> chars.size() == 26) //filter the 26th letter found
.findAny().isPresent(); //if the 26th is found, return
This way, the stream will cease as soon as the Set is filled with the 26 required characters.
There are some (even still) more efficient solutions in terms of performance below, but as a personal note I will say to not bog yourself in premature optimization too much, where you could have readability and less effort in writing the actual code.
List.remove removes by index. Since a char can be cast to an int you are effectively removing index values that do not exist, ie char 'a' is equal to int 97. As you can see your list does not have 97 entries.
You can do alphabet.remove(alphabets.indexOf(inp));
As pointed out by #Scary Wombat(https://stackoverflow.com/a/39263836/1226744) and #Kevin Esche (https://stackoverflow.com/a/39263917/1226744), there are better alternative to your algorithm
O(n) solution
static Set<Integer> alphabet = new HashSet<>(26);
public static void main(String[] args) {
int cnt = 0;
String str = "a dog is running crazily on the ground who doesn't care about the world";
for (char c : str.toCharArray()) {
int n = c - 'a';
if (n >= 0 && n < 26) {
if (alphabet.add(n)) {
cnt += 1;
if (cnt == 26) {
System.out.println("found all letters");
break;
}
}
}
}
}
Adding to #Leon answer, creating a List and removing from it seems quite unnecessary. You could simply loop over 'a' - 'z' and do a check with each char. Additionally you are looping over the whole String to find out, if each letter is present. But the better version would be to loop over each letter itself. This can potentionally safe you a few iterations.
In the end a simple example could look like this:
// This is the string- I've just put a random example
String str = "a dog is running crazily on the ground who doesn't care about the world";
str = str.toLowerCase();
boolean success = true;
for(char c = 'a';c <= 'z'; ++c) {
if(!str.contains(String.valueOf(c))) {
success = false;
break;
}
}
if (success)
System.out.println("String contains all alphabets");
else
System.out.println("String DOESN'T contains all alphabets");
Regex is your friend. No need to use a List here.
public static void main(String[] args) {
String s = "a dog is running crazily on the ground who doesn't care about the world";
s = s.replaceAll("[^a-zA-Z]", ""); // replace everything that is not between A-Za-z
s = s.toLowerCase();
s = s.replaceAll("(.)(?=.*\\1)", ""); // replace duplicate characters.
System.out.println(s);
System.out.println(s.length()); // 18 : So, Nope
s = "a dog is running crazily on the ground who doesn't care about the world qwertyuioplkjhgfdsazxcvbnm";
s = s.replaceAll("[^a-zA-Z]", "");
s = s.toLowerCase();
s = s.replaceAll("(.)(?=.*\\1)", "");
System.out.println(s);
System.out.println(s.length()); //26 (check last part added to String) So, Yes
}
Another answer has already pointed out the reason for exception. You have misused List.remove(), as it implicitly convert char to int which it called the List.remove(int) which remove by index.
The way to solve is actually easy. You can make it call the List.remove(Object) by
alphabets.remove((Character) inp);
Some other improvements:
You should use Set instead of List in this case.
You can even use a boolean[26] to keep track of whether an alphabet has appeared
You do not need to convert your string to char array. Simply do a str.charAt(index) will give you the character at certain position.
One integer variable is enough to store this information. You can do it like this
public static boolean check(String input) {
int result = 0;
input = input.toLowerCase();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c >= 'a' && c <= 'z') {
result |= 1 << (input.charAt(i) - 'a');
}
}
return result == 0x3ffffff;
}
Each bit corresponds to a letter in English alphabet. So if your string contains all letters the result will be of form 00000011111111111111111111111111
How about creating
List<String> alphabets = new ArrayList <String> ();
and add values as strings
then
for (String val : alphabets) { // if str is long this will be more effecient
if (str.contains (val) == false) {
System.out.println ("FAIL");
break;
}
}
You can get rid of the exception, by changing this line in your code
char inp = strChar[i];
to
Character inp = strChar[i];
Refer https://docs.oracle.com/javase/7/docs/api/java/util/List.html#remove(java.lang.Object)
List.remove('char') is treated as List.remove('int'), which is why you are getting indexOutOfBoundsException, because it is checking the ASCII value of 'a' which is 97. Converting variable 'inp' to Character would call List.remove('Object') api.
And if you like Java 8 streams like me:
final List<String> alphabets = new ArrayList<>();
And after filling alphabets with a-z:
final String str = "a dog is running crazily on the ground who doesn't care about the world";
final String strAsLowercaseAndWithoutOtherChars = str.toLowerCase()
.replaceAll("[^a-z]", "");
final boolean anyCharNotFound = alphabets.parallelStream()
.anyMatch(t -> !strAsLowercaseAndWithoutOtherChars.contains(t));
if (anyCharNotFound) {
System.out.println("String DOESN'T contains all alphabets");
} else {
System.out.println("String contains all alphabets");
}
This converts the string to lower case (skip if you really are only looking for the small letters), removes all characters from the string which are not small letters and then checks for all members of your alphabets if they are contained in the string by using a parallel stream.
Here's another naive solution that uses String.split("") to split every character into a String[] array, then Arrays.asList() to convert that to a List<String>. You can then call yourStringAsList.containsAll(alphabet) to determine whether your String contains the alphabet:
String yourString = "the quick brown fox jumps over the lazy dog";
List<String> alphabet = Arrays.asList("abcdefghijklmnopqrstuvwxyz".split(""));
List<String> yourStringAsList = Arrays.asList(yourString.split(""));
boolean containsAllLetters = yourStringAsList.containsAll(alphabet);
System.out.println(containsAllLetters);
This approach might not be the fastest, but I think the code is a littler easier to understand than the solutions proposing loops and streams and whatnot.
Just do something like
sentence.split().uniq().sort() == range('a', 'z')
For Java 8, it could be written like:
boolean check(final String input) {
final String lower = input.toLowerCase();
return IntStream.range('a', 'z'+1).allMatch(a -> lower.indexOf(a) >= 0);
}
Convert the string to lower case or capitals. Then loop thru the equivalent ascii decimal values for A-Z or a-z and return false if not found in character array. You will have to cast the int to char.
I've thought about playing with the ASCII codes of the characters.
String toCheck = yourString.toLowerCase();
int[] arr = new int[26];
for(int i = 0; i < toCheck.length(); i++) {
int c = ((int) toCheck.charAt(i)) - 97;
if(c >= 0 && c < 26)
arr[c] = arr[c] + 1;
}
After running the loop you eventually get an array of counters, each representing a letter of alphabet (index) and it's occurrence in the string.
boolean containsAlph = true;
for(int i = 0; i < 26; i++)
if(arr[i] == 0) {
containsAlph = false;
break;
}
Character inp = strChar[i];
Use this instead of char, List remove method have 2 overloaded methods , one with object and one with int .If you pass char its been treated as the int one.

Categories