I have a string = "1337" and I want to convert it to a list of Int, I tried to get every element in the string and convert it to Int like this string[0].toInt but I didn't get the number I get the Ascii value, I can do it with this Character.getNumericValue(number), How I do it without using a built it function? with good complexity?
What do you mean "without using a built in function"?
string[0].toInt gives you the ASCII value of the character because the fun get(index: Int) on String has a return type of Char, and a Char behaves closer to a Number than a String. "0".toInt() == 0 will yield true, but '0'.toInt() == 0 will yield false. The difference being the first one is a string and the second is a character.
A oneliner
string.split("").filterNot { it.isBlank() }.map { it.toInt() }
Explanation: split("") will take the string and give you a list of every character as a string, however, it will give you an empty string at the beginning, which is why we have filterNot { it.isBlank() }, we then can use map to transform every string in our list to Int
If you want something less functional and more imperative that doesn't make use of functions to convert there is this
val ints = mutableListOf<Int>() //make a list to store the values in
for (c: Char in "1234") { //go through all of the characters in the string
val numericValue = c - '0' //subtract the character '0' from the character we are looking at
ints.add(numericValue) //add the Int to the list
}
The reason why c - '0' works is because the ASCII values for the digits are all in numerical order starting with 0, and when we subtract one character from another, we get the difference between their ASCII values.
This will give you some funky results if you give it a string that doesn't have only digits in it, but it will not throw any exceptions.
As in Java and by converting Char to Int you get the ascii equivalence.
You can instead:
val values = "1337".map { it.toString().toInt() }
println(values[0]) // 1
println(values[1]) // 3
// ...
Maybe like this? No-digits are filtered out. The digits are then converted into integers:
val string = "1337"
val xs = string.filter{ it.isDigit() }.map{ it.digitToInt() }
Requires Kotlin 1.4.30 or higher and this option:
#OptIn(ExperimentalStdlibApi::class)
Related
Today I was trying to compare two strings with Stream API in java.
Let's assume that we have two Strings:
String str1 = "ABCDEFG"
String str2 = "ABCDEEG"
We can make streams from it with:
str1.chars().stream()...
str2.chars().stream()...
And now I want to compare these string, char by char and iterate some variable when char will be different on the same position, so the result in this case will be 1, because there is one difference in this.
I was trying to do call map or forEach from first and there my journey ends, because I don't know how to get corresponding element form second stream.
Assuming that both the strings are of same length(integer max), you can count the differences as :
int diffCount = (int) IntStream.range(0, str1.length())
.filter(i -> str1.charAt(i) != str2.charAt(i)) // corresponding characters from both the strings
.count();
Assuming that both String are of same length, you can use this way too.
long count = IntStream.iterate(0, n-> n+1)
.limit(str1.length()).filter(i -> str1.charAt(i) != str2.charAt(i)).count();
I am trying to write a function that takes a string txt and returns an int of that string's character's ascii numbers. It also takes a second argument, n, that is an int that specified the number of digits that each character should translate to. The default value of n is 3. n is always > 3 and the string input is always non-empty.
Example outputs:
string_to_number('fff')
102102102
string_to_number('ABBA', n = 4)
65006600660065
My current strategy is to split txt into its characters by converting it into a list. Then, I convert the characters into their ord values and append this to a new list. I then try to combine the elements in this new list into a number (e.g. I would go from ['102', '102', '102'] to ['102102102']. Then I try to convert the first element of this list (aka the only element), into an integer. My current code looks like this:
def string_to_number(txt, n=3):
characters = list(txt)
ord_values = []
for character in characters:
ord_values.append(ord(character))
joined_ord_values = ''.join(ord_values)
final_number = int(joined_ord_values[0])
return final_number
The issue is that I get a Type Error. I can write code that successfully returns the integer of a single-character string, however when it comes to ones that contain more than one character, I can't because of this type error. Is there any way of fixing this. Thank you, and apologies if this is quite long.
Try this:
def string_to_number(text, n=3):
return int(''.join('{:0>{}}'.format(ord(c), n) for c in text))
print(string_to_number('fff'))
print(string_to_number('ABBA', n=4))
Output:
102102102
65006600660065
Edit: without list comprehension, as OP asked in the comment
def string_to_number(text, n=3):
l = []
for c in text:
l.append('{:0>{}}'.format(ord(c), n))
return int(''.join(l))
Useful link(s):
string formatting in python: contains pretty much everything you need to know about string formatting in python
The join method expects an array of strings, so you'll need to convert your ASCII codes into strings. This almost gets it done:
ord_values.append(str(ord(character)))
except that it doesn't respect your number-of-digits requirement.
I need to split a uint to a list of bits (list of chars, where every char is "0" or "1", is also Ok). The way I try to do it is to concatenate the uint into string first, using binary representation for numeric types - bin(), and then to split it using str_split_all():
var num : uint(bits:4) = 0xF; // Can be any number
print str_split_all(bin(num), "/w");
("/w" is string match pattern that means any char).
The output I expect:
"0"
"b"
"1"
"1"
"1"
"1"
But the actual output is:
0. "0b1111"
Why doesn't it work? Thank you for your help.
If you want to split an integer into a list of bits, you can use the %{...} operator:
var num_bits : list of bit = %{num};
You can find a working example on EDAPlayground.
As an extra clarification to your question, "/w" doesn't mean match any character. The string "/\w/" means match any single character in AWK Syntax. If you put that into your match expression, you'll get (almost) the output you want, but with some extra blanks interleaved (the separators).
Regardless, if you want to split a string into its constituting characters, str_split_all(...) isn't the way to go. It's easier to convert the string into ASCII characters and then convert those back to string again:
extend sys {
run() is also {
var num : uint(bits:4) = 0xF; // Can be any number
var num_bin : string = bin(num);
var num_bin_chars := num_bin.as_a(list of byte);
for each (char) in num_bin_chars {
var char_as_string : string;
unpack(packing.low, %{8'b0, char}, char_as_string);
print char_as_string;
};
};
};
The unpack(...) syntax is directly from the e Reference Manual, Section 2.8.3 Type Conversion Between Strings and Scalars or Lists of Scalars
I am a novice programmer and I am trying to compare two characters from different strings, such that I can give an arbitrary index from each string and check to see if they match. From the processing website it seems that you can compare two strings, which I have done, but when I try to do so with characters it seems that the arguments (char,char) are not applicable. Can someone tell me where I am going wrong? Thanks.
You can use String's charAt() method/function to get character from each string at the desired index, then simply compare:
String s1 = ":)";
String s2 = ";)";
void setup(){
println(CompareCharAt(s1,s2,0));
println(CompareCharAt(s1,s2,1));
}
boolean CompareCharAt(String str1,String str2,int index){
return s1.charAt(index) == s2.charAt(index);
}
Note that when you're comparing strings == doesn't help, you need to use String's equal()
String s1 = ":)";
String s2 = ";)";
println(s1.equals(s2));
println(s1.equals(":)"));
Also, if data comes from external sources, it's usually a good idea to compare both strings at using the same case:
println("MyString".equals("myString"));
println("MyString".toLowerCase().equals("myString".toLowerCase()));
maybe you can pass the argument after converting(typecasting) the char to string.
(string(char),string(char))
Yep. Just use == as it gets interpreted as a char datatype.
This is assuming you've split the char from the String...
char a = 'a';
char b = 'a';
if(a == b) {
// etc
}
As mentioned above, use .equals() for String comparison.
String a = "a";
String b = "a";
if(a.equals(b)) {
// etc
}
Also, the proper way to cast a char as a String is str() not string()
I was asked in a Java interview to write a program that would convert a string for example "123" into number 123 without using any of java's conversion functions/utility classes.
I am still confused if that would be possible. Any ideas ?
Thanks
Break the string into individual characters, map each to its numeric value, and combine by multiplying each by its place value.
I should have made my comment an answer so I can get the answer credit :)
"what counts as a utility class? Could you have a map of strings to numbers, iterate over the string, look up the number by the string, and construct the number?"
in pseudocode:
Map<String, Integer> = {
"0":0,
"1":1,
"2":2,
... etc }
int number = 0;
for(i=string.length-1; i>=0; i--){
String substr = string.substring(i, i+1);
int digit = map.get(substr);
number += 10^(string.length-i)*digit;
}
return number