How can I convert each item of a char[] (char array) to its ascii code? char_arr[i].charAt(0) doesn't work as the method doesn't exist. I can't use the toString method for char_arr[i].
import java.util.Scanner;
/**
* Created by mona on 2/25/16.
*/
public class FunnyString {
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
int num_str;
num_str=sc.nextInt();
Boolean flag=true;
for (int i=0;i<num_str;i++){
StringBuilder strb = new StringBuilder(scan.nextLine());
StringBuilder str_reverse=strb.reverse();
Char[] strb_arr=strb.toString().toCharArray();
Char[] strb_rev_arr=str_reverse.toString().toCharArray();
for (int i=1; i<strb_arr.length;i++){
if (Math.abs(strb_arr[i]-strb_arr[i-1])!=Math.abs(strb_rev_arr[i]-strb_rev_arr[i-1])){
flag=false;
}
}
}
if (flag==false){
System.out.println("Not funny");
}
else{
System.out.println("Funny");
}
}
}
You can try this: cast it to int
char[] chars;
for (char aChar : chars) {
System.out.println("chars = " + (int) aChar);
}
Traverse through the array, assigning each char value to an int by casting, i.e.,
char_to_ascii[i] = (int) char_arr[i] ;
You can use casting to integer (int) , or just add 0 to your char.
See this
char[] cs = {'a', 'b', 'c'};
for (Character c : cs)
{
System.out.println(c + 0);
}
Output
97
98
99
See it's ascii codes of given chars http://www.asciitable.com/ .
Additionally you could get a char from a numeric value.
char[] cs = {'a', 'b', 'c'};
for (Character c : cs)
{
System.out.println(c + 0);
System.out.println( (char)(c + 0) );
}
Output
97
a
98
b
99
c
Because elements of char[] are UTF-16 code units, the standard numerical representation is in the form of backslash, "u", four hexadecimal digits. For example, 'a' is represented as '\u0061'.
Also, note that some Unicode codepoints are encoded in two UTF-16 code units. For example, the musical quarter note "𝅘𝅥" (might not display with the font your browser is using with this web page).
for (char c : "abc𝅘𝅥123".toCharArray())
{
System.out.println(String.format("\\u%04X", (int)c));
}
Related
I've been trying to see if there is a way of solving this problem with a double loop. Looping over each word in the array and checking to see if all of the chars provided exist in that word.
Broken keyboard Problem:
Input A = "Hello, my dear friend!"
Input B = ['h', 'e', 'l, 'o', 'm']
We have a broken keyboard here in which only the alphabet keys (both lower case and upper case) in list B, number keys and punctuation keys work.
Write the function which take a string A and list of char B, and return how many words we can type.
Explanation
input: A "Hello, my dear friend!", B = ['h', 'e', 'l, 'o', 'm'] output: 1
Explanation: For the first word "Hello," (including the comma), we can find every char in list B.
Since all punctation key works fine, so output++.
For the second word "my", we only can find char 'm' in list B, so we can't type the whole word. Then the same, "dear", can't find char 'd', so continue; "friend!", can't find char 'f', so continue;
This is what I have tried so far, but I can't use String's .contain() method as it only accepts a char sequence not a char array. How can I check each individual word for an array of chars using JAVA?
Thanks in advance, any support is appreciated.
public class BrokenKeyboard
{
public static void main(String[] args)
{
String stringText = "Hello my dear friend";
char [] charLetterArray = {'h', 'e', 'l', 'o', 'm'};
howManyWordsCalc(stringText, charLetterArray);
}
// Only words from stringText that can be typed in whole should be printed.
// If the letters present in the word aren't present in charLetterArray they don't get printed
public static int howManyWordsCalc(String text, char[] letters)
{
int wordCount = 0;
// sanitise input
if (text.isEmpty())
{
return 0;
}
else
{
text = text.toLowerCase();
String[] stringSeparated = text.split(" ");
for (int i = 0; i < stringSeparated.length; i++)
{
System.out.println(stringSeparated[i]);
for (int j = 0; j < letters.length; j++)
{
// stringSeparated[i].contains(letters)
if (stringSeparated[i].contains())
{
wordCount++;
}
}
}
return wordCount;
}
}
}
Here's a sample solution:
public class Main{
public static void main(String[] args){
String stringText = "Hello my dear friend";
char [] charLetterArray = {'h', 'e', 'l', 'o', 'm'};
System.out.println(howManyWordsCalc(stringText, charLetterArray));
}
// Only words from stringText that can be typed in whole should be printed.
// If the letters present in the word aren't present in charLetterArray they don't get printed
public static int howManyWordsCalc(String text, char[] letters){
int wordCount = 0;
// sanitise input
if (text.isEmpty()){
return 0;
}
else{
text = text.toLowerCase();
String[] stringSeparated = text.split(" ");
for (int i = 0; i < stringSeparated.length; i++){
int validLetters = 0;
for(int j = 0; j < stringSeparated[i].length(); j++){
for(char c: letters){
if(c == stringSeparated[i].charAt(j)){
validLetters++;
break;
}
}
}
if(validLetters == stringSeparated[i].length()){
wordCount++;
}
}
return wordCount;
}
}
}
The way that this code works is exactly the same as yours, except the algorithm for checking whether or not a word can be made up of available letters.
The algorithm that I first iterate through every word in the array. Then, I create an integer called validLetters, where we will check how many letters in the word we can type. If the number of validLetters is equal to the length of the word, then the word can be typed.
To check whether a letter can be typed, we will loop through every letter in the word, and see if it is inside of the array letters. If it is, we increase our validLetters and exit the loop.
Alternatively, if you want to strictly do this in two for loops, this is a shortened version:
import java.util.*;
public class Main{
public static void main(String[] args){
String stringText = "Hello my dear friend";
char [] charLetterArray = {'h', 'e', 'l', 'o', 'm'};
System.out.println(howManyWordsCalc(stringText, charLetterArray));
}
// Only words from stringText that can be typed in whole should be printed.
// If the letters present in the word aren't present in charLetterArray they don't get printed
public static int howManyWordsCalc(String text, char[] letters){
int wordCount = 0;
// sanitise input
if (text.isEmpty()){
return 0;
}
else{
text = text.toLowerCase();
String[] stringSeparated = text.split(" ");
for (int i = 0; i < stringSeparated.length; i++){
int validLetters = 0;
for(int j = 0; j < stringSeparated[i].length(); j++){
if (new String(letters).indexOf(stringSeparated[i].charAt(j)) != -1) {
validLetters++;
}
}
if(validLetters == stringSeparated[i].length()){
wordCount++;
}
}
return wordCount;
}
}
}
Let me know if you have any questions/clarifications!
I changed it a little bit, have a look:
public static void wordCalc(String input, char[] chars) {
String[] inputWords = input.toLowerCase().split(" ");
boolean[] allLetters = new boolean[26];
for(int i=0; i<chars.length; i++) {
allLetters[chars[i] - 'a'] = true;
}
int wordCount = 0;
for(String word : inputWords) {
boolean isWordPossible = true;
for(int i=0; i<word.length(); i++){
if(!allLetters[word.charAt(i) - 'a']){
isWordPossible = false;
break;
}
}
if(isWordPossible) {
System.out.println("word " + word + " is possible");
wordCount++;
}
}
System.out.println(wordCount);
}
I found this really neat trick on the internets once. Storing the allowed letters in a boolean array. That way, when you want to check if a char is allowed, you can just check the value of the array at index corresponding to that char!
This does bring me to an important note however. Chars are stored as ints, which is why you can cast them back and forth and do funky stuff like word.charAt(i) - 'a' (that will give you the position in the boolean array because it will give you the distance between the letter "a" and whatever letter is at position "i" in the word").
Strings are ultimately char arrays. So you can do:
char[] stuff = someString.toCharArray();
Its also pretty important to note that strings are immutable, and string literals point to the same object.
Final note on time complexity, its best to avoid nesting loops as much as possible. If you have loads of input, it will become really slow! If you have one loop, it's O(n) time, 2 loops its already O(n^2), which is quite slow as far as time complexity goes. I can't think of a different way for this case however. The structures you use and method of access can hugely impact performance. I think you'll really like HashSets, especially for this problem where allowed characters are unique anyway.
You could just check if all the characters in the word are contained in letters character array by using another loop (which actually has the same complexity as String::contains).
Also, I'd suggest to get the words by splitting on repeated punctuation and/or whitespace characters using [\p{Z}\p{P}]+ regex where \p{Z} stands for whitespaces and \p{P} for punctuation.
public static int howManyWordsCalc(String text, char[] letters) {
int wordCount = 0;
String[] words = text.toLowerCase().split("[\\p{P}\\p{Z}]+");
for (String word : words) {
// System.out.print("'" + word + "'\t");
boolean allFound = true;
for (char c : word.toCharArray()) {
boolean found = false;
for (char letter : letters) {
if (c == letter) {
found = true;
break;
}
}
if (!found) {
// System.out.println("not found letter: " + c + " in word " + word);
allFound = false;
break;
}
}
if (allFound) {
wordCount++;
// System.out.println("all found");
}
}
return wordCount;
}
Test:
System.out.println(howManyWordsCalc(
"Hello, my dear friend!", new char[] {'h', 'e', 'l', 'o', 'm', 'y'}
));
Output (with debug prints enabled):
'hello' all found
'my' all found
'dear' not found letter: d in word dear
'friend' not found letter: f in word friend
2
I have tried same in c#, but you also can use the HashSet collection and try the same. Java HashSet also has Contains().
I hope this will be helpful.
class Program
{
static void Main(string[] args)
{
string a = "Hello, my dear friend!";
string A = a.ToUpper();
string[] seperate = A.Split(new Char[] { ' ', ',', '.', '-', '\n', '\t', '!' });
HashSet<Char> hash = new HashSet<char>();
hash.Add('H');
hash.Add('E');
hash.Add('L');
hash.Add('O');
hash.Add('M');
int count = 0;
bool flag = true;
foreach (var w in seperate)
{
if (w.Length > 0) {
Char[] ca = w.ToCharArray();
foreach (var d in ca)
{
if(!hash.Contains(d))
{
flag = false;
break;
}
}
if(flag)
{
flag = true;
count++;
}
}
}
Console.WriteLine("Count : " + count);
Console.Read();
}
}
I am developing a method which takes ArrayList as an argument.
Then, the method makes some changes into the array and returns transformed arrayList.
The input array is going to be like that {A123, C123, 15B2} and I would like to get the following output {Aa123, Cc123, 15Bb2}.
That is to say, after any capital letter I need to add the same lowercase letter.
And there are any order and quantity of letters, e.g. it is also possible to get strings like those Hkjk124, hy71.
The method is shown below:
protected ArrayList<String> enrichValues(ArrayList<String> list) {
for (int i = 0; i < list.size(); i++) {
char[] charArray = list.get(i).toCharArray();
List<Character> listChars = new ArrayList<>();
for (char c : charArray) {
listChars.add(c);
}
for (int j = 0; j < listChars.size(); j++) {
if (listChars.get(j).charValue() == 'A') {
listChars.add(j + 1, 'a');
}
}
String newChar = "";
for (Character c : listChars)
newChar += c.toString();
list.set(i, newChar);
}
return list;
}
The main problem I have faced to is that I do not know how to check if a letter is uppercase.
I failed to apply something like:
if(Character.isLetter(c) && Character.isUpperCase(c)) {
listChars.add(j + 1, 'a');
}
Because of that I have to add lots of checks:
if (listChars.get(j).charValue() == 'B') {
listChars.add(j + 1, 'b');
}
if (listChars.get(j).charValue() == 'C') {
listChars.add(j + 1, 'c');
}
But it is a very bad approach. I would appreciate any help.
Here's a way of doing it that works like a charm :
public static ArrayList<String> enrichValues(ArrayList<String> values){
ArrayList<String> array = new ArrayList<String>();
for (String str : values){ //For each string
StringBuilder copy = new StringBuilder();
for (char c : str.toCharArray()) {//For each char
copy.append(c);
if(Character.isLetter(c) && Character.isUpperCase(c)){
copy.append(Character.toLowerCase(c));
}
}
array.add(copy.toString());
}
return array;
}
Example :
public static void main(String[] args) {
String a = "A123";
String b = "C123";
String c = "15B2";
String d = " Hkjk124";
String e = "hy71";
String g = "AbCdE645 DeeeFFD";
ArrayList<String> values = new ArrayList<String>();
values.add(a);
values.add(b);
values.add(c);
values.add(d);
values.add(e);
values.add(g);
values = enrichValues(values);
System.out.println(values.toString());
}
Output : [Aa123, Cc123, 15Bb2, Hhkjk124, hy71, AabCcdEe645 DdeeeFfFfDd]
When you are writing some method which accepts concrete implementation of the List interface such as ArrayList, consider to change it to List type. This will allow you to pass in any form of list: LinkedList, ArrayList, ...
Another thing you shoud know is, that joining strings via += is inefficient, as it creates new String instance each time += is applied. Instead of doing this, you should use StringBuilder which allocates resizable buffer for string where you can append other characters.
Condition Character.isLetter(c) && Character.isUpperCase(c) is redudant, since Character.isUpperCase(char) already returns false for non-letter characters.
If you need to convert character to lower-case use Character.toLowerCase(char).
Note, characters are basically integers, so when you write something like this: char c = 65; and print the value, you will see 'A' in output, because 65 is ASCII value for character 'A'. If you add 32, you will obtain 97 which is 'a'. Putting all together you can write something like this:
char c = ...;
// c is in range of upper-case characters
if (c >= 65 && c <= 90) {
char lower = c + 32;
}
// c is in range of lower-case characters
if (c >= 97 && c <= 122) {
char upper = c - 32;
}
Try following method which mutates original list:
protected List<String> enrichValues(List<String> list) {
for (int i = 0; i < list.size(); i++) {
StringBuilder sb = new StringBuilder(list.get(i));
for (int j = 0; j < sb.length(); j++) {
char c = sb.charAt(j);
if ( Character.isUpperCase(c) ) {
sb.insert(++j, Character.toLowerCase(c));
}
}
list.set(i, sb.toString());
}
return list;
}
or this one which creates new list for transformed values:
protected List<String> enrichValues(List<String> original) {
List<String> transformed = new ArrayList<>(list.size());
for (String s : original) {
StringBuilder sb = new StringBuilder(s);
for (int j = 0; j < sb.length(); j++) {
char c = sb.charAt(j);
if ( Character.isUpperCase(c) ) {
sb.insert(++j, Character.toLowerCase(c));
}
}
transformed.add(sb.toString());
}
return transformed;
}
Test:
System.out.println( enrichValues(Arrays.asList("A123", "C123", "15B2")) );
// Output: [Aa123, Cc123, 15Bb2]
To find out whether if a letter is upper case you just need to use the ASCII alphabet. Upper case characters go from 65 to 90.
So you just need to use a loop over the length of your string and check for each char if it´s ASCII value is between 65 and 90. So it would look like this, assuming the variable temp is one character of the string:
if((int)temp >= 65 && (int)temp <= 90){
//Add the lower case character by adding 22 to the character value (lower case are from 97-122)
char additionalChar = ((int)temp)+22;
}
Note that I´ve not tried the code so ((int)temp)+22 might not work that way, but it would look pretty similar.
There is an easier way to do this with regular expressions:
final ArrayList< String > outputList = new ArrayList<>();
for ( String str : list ) {
final String[] letters = str.replaceAll( "[^A-Z]", "" ).toLowerCase().split( "" );
final String result = String.format( str.replaceAll( "([A-Z])", "$1%s" ), letters );
outputList.add( result );
}
return outputList;
So i have a program where i want to replace specific characters in the program with other letters. However, when i run this program, it seems to keep reverting the changed characters back. This is the code so far:
public static String changeSample(String sample) {
for (int i = 0; i < sample.length(); i++) {
if (sample.charAt(i) == 'A') {
sample = sample.replace(sample.charAt(i), 'B');
continue;
}
else if (sample.charAt(i) == 'B') {
sample = sample.replace(sample.charAt(i), 'A');
continue;
}
}
return sample;
Is there a way that i can iterate through each character in the string and then check if it is either an A, B, C, D, E, or F and change it to its complimentary letter, i.e. A to B, B to A, C to D, D to C, E to F, F to E.
replace() will return a new String where ALL occurrences of a particular character are changed, not just a character at a particular position. So your problem is that the repeated replace() statements are effectively modifying the values back and forth.
Because a String is immutable, you cannot simply replace its characters with others dynamically. So, convert your code to use a StringBuilder instead.
StringBuilder buildSample = new StringBuilder();
buildSample.append(sample);
Now you can use setCharAt() instead of replace() to change the character at one position at a time.
buildSample.setCharAt(i, 'A');
At the end, you can return buildSample.toString().
As for changing each letter A to F to its complement, if only these six letters are required, a hard-coded function with a switch statement would do. Otherwise you can use a function like complementaryLetter() below, which returns the complement after checking the ASCII value of the character. This will work for all characters. You can add code to handle invalid cases, for non-character input.
A complete working code:
public class Replace {
public static void main(String[] args) {
String s1 = "ABCDEFA";
System.out.println(s1);
s1 = changeSample(s1);
System.out.println(s1);
}
public static char complementaryLetter(char letter) {
char retChar = 'A';
if ((int) letter % 2 == 0)
retChar = (char) ((int)letter - 1);
else
retChar = (char) ((int) letter + 1);
return retChar;
}
public static String changeSample(String sample) {
StringBuilder buildSample = new StringBuilder();
buildSample.append(sample);
for (int i = 0; i < sample.length(); i++) {
buildSample.setCharAt(i, complementaryLetter(sample.charAt(i)));
}
return buildSample.toString();
}
}
Take the example:
System.out.println("Hello Uni\u03C0");
System.out.println("Hello Esc \\");
this gives something like
Hello Uniπ
Hello Esc \
Is there a way where I can give different values to 03C0 and \ during different iterations in a loop?
for example
something like
System.out.format("Hello Esc \%c",'\\');
System.out.format("Hello Esc \%c",'\"');
I know this will give compiler error. I want to know how this can be done.
For example, I would like to print a different unicode character (say from \u0000 to \u00C3) in each iteration of a loop.
For example, I have this function that returns the 4 digit hexadecimal value of an integer:
public static String hexa(int a)
{
int x=a;
String b= String.format("%x",x);
if(b.length() == 1)
{
b="000"+b;
}
if(b.length() == 2)
{
b="00"+b;
}
if(b.length() == 3)
{
b="0"+b;
}
return b;
}
Now I would like to join \u with hexa(i) to get different unicode character for different i
You don't even have to convert the integer to hex string. Leave it as an integer and use Character.toChars()
StringBuilder sb = new StringBuilder();
sb.append(Character.toChars(0x03C0));
System.out.println(sb.toString());
Further example showing a for loop:
public static void main(String [] args) {
String lineSeparator = System.lineSeparator();
StringBuilder sb = new StringBuilder();
for(int i = 0x03C0; i < 0x03D0; i++) {
sb.append(Character.toChars(i)).append(lineSeparator);
}
System.out.println(sb.toString());
}
Output:
π
ρ
ς
σ
τ
υ
φ
χ
ψ
ω
ϊ
ϋ
ό
ύ
ώ
Ϗ
One last clarification:
System.out.println(Character.toChars(0x03C0)[0] == '\u03C0');
Output:
true
Example without StringBuilder:
String foo = "";
for(char c : Character.toChars(0x03C0)) {
foo += c;
}
System.out.println(foo);
how can I create a loop that also turns string "abcc" into the sum of their letter position, say a=1 b=2 c=3 and it sums the string 1+2+3+3=9.
import java.util.Arrays;
public class Test
{
public static void main(String[] args)
{
String original = "hello";
char[] chars = original.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);
System.out.println(sorted);
}
}
You can use the ASCII values. a has value 97, b has 98 and so on.
private int printSum(String original){
int sum = 0;
if(original!=null){
char[] arr = original.toLowerCase().toCharArray();
for(int x :arr){
sum+= (x-96);
}
}
return sum;
}
You can make use of the fact that characters can be cast to an Integer, and thereby take on their ASCII value. e.g. System.out.println((int)'a') would print '97'. Knowing that, you only have to subtract a certain number based on whether it's an upper- or lowercase letter and you get 1 for a, 2 for b etc.
Remove non-alphabet characters from the string using regular expressions
Modify string with toLower() or toUpper()
Convert the string into charArray
Set initial result as 0
Foreach char in the array, subtract the char value with 64 (if you use UPPERCASE) or 96 (if you use lowercase) and add it into result
Here are two solutions: One with a loop as requested, and one with recursion.
This works with both upper- and lowercase letters, but doesn't take non-alphabetical letters into account. This can easily be tested for in an if-statement, with the following criteria: Character.isAlphabetic( c ).
public class Main {
static final int LOWERCASE_OFFSET = 96;
static final int UPPERCASE_OFFSET = 64;
public static void main( String[] args ){
System.out.println(recursion( "Abcc" ));
}
static int recursion( String str ) {
if( str.isEmpty() )
return 0;
char c = str.charAt( 0 );
int charVal = Character.isUpperCase( c ) ? c - UPPERCASE_OFFSET : c - LOWERCASE_OFFSET;
return charVal + recursion( str.substring( 1 ) );
}
static int loop( String str ) {
int val = 0;
for( char c : str.toCharArray() ) {
val += Character.isUpperCase( c ) ? c - UPPERCASE_OFFSET : c - LOWERCASE_OFFSET;
}
return val;
}
}