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();
Related
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)
I'm using C/C++, I have a problem with string.
I have a string s1 = 'p^(qvr)<->~q' and I want to merge 3 elements s1[7] = '<', s1[8] = '-', s1[9] = '>' into 1 element in string s2, which means that s2 = p^(qvr)<->~q but s2[7] = '<->'. How can I do this?
You cannot, a string is an array of chars, thus accessing a string-element via [] gives you a single char. What you want is an array of strings, so just use a std::vector of std::string.
Scanner input = new Scanner(System.in);
String userInput = input.nextLine();
String letterArray[] = new String[userInput.length()];
for(int i = 0; i < userInput.length(); i++ ){
letterArray[i] = userInput.substring(i, i+1);
}
for(int j = userInput.length()-1; j>=0; j--){
System.out.print(letterArray[j]);
}
I have stored the users input now I want to reverse what they have inputted and store the reversed form as a String.
I have managed to display the String as a superposition of each letter increment which has been stored in an Array, how do I go about storing the reversed form as a String?
If you just want to print it reverse you can do that:
Scanner input = new Scanner(System.in);
String userInput = input.nextLine();
for(int i=1;i<=userInput.length();i++){
System.out.print(userInput.charAt(userInput.length()-i));
}
Other than that if you wanto to turn string to array you can use simpler methods like: String[] letterArray = userInput .split("");
If you want to store it as an array or as a new string you can do this:
Scanner input = new Scanner(System.in);
String userInput = input.nextLine();
Char[] characters=new Char[userInput.length];
for(int i=1;i<=userInput.length();i++){
characters[i-1]=userInput.charAt(userInput.length()-i);
System.out.print(characters[i-1]);
}
String newString=new String(characters);
There are many possibilities.
You can obtain the reversed java.lang.String in different ways.
The safest would be using the java.lang.StringBuilder.reverse() method:
System.out.println(new java.lang.StringBuilder("abc").reverse().toString());
If you want to learn how to iterate the characters and add them in the way you want, you can use the StringBuilder, appending the characters one by one with the java.lang.StringBuilder.append(char c) method.
WARNING: uncommon case ahead.
There is an special case where you cannot alter the order of the characters, not even reverse them.
It refers to the surrogate pairs of UTF-16. Those are pairs of individual characters in the Java java.lang.String (say chars c1 and c2) but actually refer to a single unicode character.
If you build an string reversing the chars in that pair (c2 then c1), you would be building an incorrect string.
Update: I have just seen that the documentation of the StringBuider.reverse() method describes this about surrogate pairs explicitly. Read it here: http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#reverse()
I need to sort my Linked List, the problem is that each of my Linked List elements are Strings with sentences. So the question is... how to detect each number in my Linked List and get the value?.
I tried to split my linked list so I can pass trough each element.
private LinkedList<String> list = new LinkedList<String>();
list.add("Number One: 1")
list.add("Number Three: 3")
list.add("Number two:2")
for(Iterator<String> iterator =list.iterator(); iterator.hasNext(); )
{
String string = iterator.next();
for (String word : string.split(" ")){
}
I also tried with "if((word.contains("1") || (word.contains("2")...." inside the for loop, and then pass the value "word" to Double... but I think is not very smart
So my goal is this Output (Number One: 1 , Number Two: 2, Number Three: 3), therefore I need the value of each number first.
why not use tryParse on the string,
for (String word : string.split(" ")){
int outvalue
if(int.TryParse(word, outvalue)){
//DoSomething with result
}
}
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()