Currently I have a simple problem to solve:
Given a String str, what is the best way of counting the amount of alphabetic literals in the string?
Right now I am thinking something like this:
int letterCount = 0;
for(int i = 0 : str){
String check = "" + str.charAt(i);
if(check.isLetter())
letterCount++
}
Are there any more efficient or elegant ways?
I’m pretty fond of streams (since Java 8):
String str = "A string";
long letterCount = str.chars().filter(Character::isLetter).count();
System.out.println(letterCount);
7
Your for loop is another nice solution. Here’s a version that works:
for (int index = 0; index < str.length(); index++) {
if (Character.isLetter(str.charAt(index))) {
letterCount++;
}
}
String str = "#CodeWines65";
int upper = 0, lower = 0, number = 0, special = 0;
for(int i = 0; i < str.length(); i++)
{
char ch = str.charAt(i);
if (ch >= 'A' && ch <= 'Z')
upper++;
else if (ch >= 'a' && ch <= 'z')
lower++;
else if (ch >= '0' && ch <= '9')
number++;
else
special++;
}
System.out.println("Lower case letters : " + lower);
System.out.println("Upper case letters : " + upper);
System.out.println("Number : " + number);
System.out.println("Special characters : " + special);
// If you are not concerned about uppercase or lowercase you can add them both & get the total count
Related
I am trying to challenge the Caesar Cipher problem, but am stuck at one condition, the question not only move n element position but also keep loop internally in the ASCII range, so 'z' will go to 'c' not '|' if n=3.
Could someone enlighten me how to get loop inside of Character.isLetter and Character.isLowerCase base on what I am doing now? hope I am on the track, and here is my code. Thank you
public static String caesarCipher(String s, int k) {
if(k>26){
k = k % 26;
}else if (k<26){
k = (k % 26) + 26;
}
String result = new String();
int length = s.length();
for(int i=0; i<length; i++){
char ch = s.charAt(i);
if(Character.isLetter(ch)){ // only for alphabet
if(Character.isLowerCase(ch)){ // for lower case a-z
char cha = (char)(ch+k);
if(cha > 'z'){
result += (char)(ch - (26 - k));
} else {
result += cha;
}
} else if(Character.isUpperCase(ch)){ // for upper case a-z
char cha = (char)(ch+k);
if(cha > 'Z'){
result += (char)(ch - (26 - k));
}else {
result += cha;
}
}
} else {
result += ch;
}
}
return result;
}
How can I add 0 in front of every single digit number? I mean 1 to 01 etc.
I have tried to add ifs like
if(c >='A' && c<= 'I')
str = "0"+str;
but it just adds 0 in front of everything like abcd converts to 00001234 not 01020304.
This is my code.
String A[] = new String[size];
for (int i = 0; i < size; i++) {
A[i] = jList1.getModel().getElementAt(i);
String[] Text = A[i].split("");
String s = jList1.getModel().getElementAt(i);
String str = ("");
for (int z = 0; z < Text.length; z++) {
for (int y = 0; y < Text[z].length(); y = y + 1) {
char c = s.charAt(z);
if (c >= 'A' && c <= 'Z') {
str += c - 'A' + 1;
} else if (c >= 'a' && c <= 'z') {
str += c - 'a' + 1;
} else {
str += c;
}
}
str = str + "";
}
}
This Worked for me
public String addZero(int number)
{
return number<=9?"0"+number:String.valueOf(number);
}``
One way to do this would be to use a StringJoiner with Java 8:
String s = "abcdABCD";
s = s.chars()
.mapToObj(i -> Integer.toString((i >= 'a' && i <= 'z' ? i - 'a' : i - 'A') + 1))
.collect(Collectors.joining("0", "0", "")));
System.out.println(s);
>> 0102030401020304
String str = "abcd-zzz-AAA";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char ch = str.toLowerCase().charAt(i);
if (ch >= 'a' && ch <= 'z') {
sb.append('0');
sb.append(ch - 'a' + 1);
} else {
sb.append(ch);
}
}
Result: abcd-zzz-AAA -> 01020304-026026026-010101
Final fix :-)
use String#chars to get a stream of its characters, then for each one do the manipulation you want.
public class Example {
public static void main(String[] args) {
String s = "aBcd1xYz";
s.chars().forEach(c -> {
if (c >= 'a' && c <= 'z')
System.out.print("0" + (c - 'a' + 1));
else if (c >= 'A' && c <= 'Z')
System.out.print("0" + (c - 'A' + 1));
else
System.out.print(c);
});
}
}
Ouput:
0102030449024025026
You can add zero in front of single digit number using String.format.
System.out.println(String.format("%02d",1));
System.out.println(String.format("%02d",999));
The first line will print 01, second line prints 999 no zero padding on the left.
Padding zero with length of 2 and d represents integer.
I hope this helps.
Take following code as base:
for (int i = 0; i < 26; i++)
{
alphabet[i] = (char) ('A'+ i );
}
My question is: -
If 'A' Changes to 'X' how can we achieve the alphabet to reset from the start?
For example XYZABC
Whenever you have something that should "wrap around", have a look at the modulo operator. The basic idea is: you don't want to count from i=0 to 26, but e.g. from i=23 to 49, but only add the modulo-26 value to it.
Instead of starting to count at 23 (which would be kind of 'X' - 'A'), you can directly integrate this offset into your loop:
for (int i = 0; i < 26; i++)
{
alphabet[i] = (char) ('A' + ('X' - 'A' + i) % 26);
}
'A' is the base, 'X' - 'A' builds that offset where you add i to, and then take the modulo of 26 (as the alphabet has 26 characters), and then add that to your 'A' again.
You can just insert an if statement:
char startChar = 'X';
for (int i = 0; i < 26; i++) {
char ch = (char) (startChar + i);
if (ch > 'Z') {
ch -= 26;
}
alphabet[i] = ch;
}
(EDITED)
My problem statement: write a method that will encode the String passed to the method by adding 13 letters to each character in the String. If the letter after adding 13 exceeds 'z' then "wrap around" the alphabet. Then return the encoded String.
encodeString("hello") → "uryyb"
encodeString("pie") → "cvr"
encodeString("book") → "obbx"
this is what I have so far :
public static String encodeString (String input) {
String output;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c >= 'a' && c <= 'm')
c += 13;
else if (c >= 'n' && c <= 'z')
c -= 13;
output= (" " + (c));
}
return output;
}
now I know that I have to create a counter so that the method will continue to loop until it reaches the length of the string passed...and I know that if the charAt(index) is less than the character 'n' that I add 13 and if it is greater then I subtract 13. when I put it all together though I just get so confused and just get a bunch of compiling errors like Type mismatch: cannot convert from int to String.
note straightforward explanations/answers would be much appreciated...
***so now my problem is that it keeps telling me my output variable may not have been initialized
This code is not the most performatic but works good with Upper and Lower characters.
hElLo → uRyYb
pIe → cVr
bOoK → oBbX
private static String encodeString(String string) {
char[] ret = new char[string.length()];
for (int i = 0; i < string.length(); i++) {
ret[i] = rot13(string.charAt(i));
}
return String.valueOf(ret);
}
public static char rot13(char c) {
if (Character.isLetter(c)) {
if (Character.compare(Character.toLowerCase(c), 'a') >= 0
&& Character.compare(Character.toLowerCase(c), 'm') <= 0)
return c += 13;
else
return c -= 13;
}
return c;
}
You have to initialize your output variable as an empty String. Furthermore you are always replacing the contents of the output variable with the last char you've just encoded. So you have to add every char to the output with += instead of =.
So here is the fixed solution:
public static String encodeString(String input) {
String output = ""; // initialize as empty String
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c >= 'a' && c <= 'm') {
c += 13;
} else if (c >= 'n' && c <= 'z') {
c -= 13;
}
output += " " + c; // add all chars to the String instead of replacing the whole String with "="!
}
return output;
}
I beautified your code a bit, so everybody can see what it really does.
Use an IDE!
I'm getting String out of range
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range:
5 at java.lang.String.charAt(String.java:658) at
Lab6.DataSentinelWhile3.main(DataSentinelWhile3.java:24)
public static void main(String[] args) {
String sentence;
char ch = 'a';
int ind = 0, upperLetter=0, lowerLetter=0, digits=0, punctuation=0;
Scanner input = new Scanner(System.in);
System.out.print("Please enter a sentence (full-stop to terminate):");
sentence = input.nextLine();
while(ch != '.') {
if(ch >= 'a' && ch <= 'z')
lowerLetter++;
else if(ch >= 'A' && ch <= 'Z')
upperLetter++;
else if(ch >= '0' && ch <= '9')
digits++;
else
punctuation++;
ind++; //increase the index of the sentence by 1
ch = sentence.charAt(ind); //extract every character from sentence
}
System.out.print("\n\n*****Lexical Analysis of your Sentence*****" +
"\nLowercase letters: " + lowerLetter +
"\nUppercase letters: " + upperLetter +
"\nDigits: " + digits +
"\nPunctuation symbols: " + (punctuation+1));
input.close();
}
Use forloop when possible, possibility of error reduces by 10 folds:, for while loop:
ind i = 0;
while(ind < sentence.length){
ch = sentence.charAt(ind);
if(ch == '.') break;
if(ch >= 'a' && ch <= 'z')
lowerLetter++;
else if(ch >= 'A' && ch <= 'Z')
upperLetter++;
else if(ch >= '0' && ch <= '9')
digits++;
else
punctuation++;
ind++;
}
try this loop
while(ind < sentence.length)
{
}
change this
ch = sentence.charAt(ind);
ind++;
while(ch != '.')
You should set your loop on the string length, if sentence doesn't end with a final dot "." it doesn't stop.