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()
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();
My starting point is a string separated by commas, containing a variable number of integers e.g.:
System::String^ tags=gcnew String("1,3,5,9");
Now I would like - with the least amount of steps possible - convert this string into a Integer list:
List<System::Int32>^ taglist= gcnew List<System::Int32>();//to contain 1,3,5,9
Additionally, after manipulating the list, I need to export it back to a string at the end of the day. I saw the question being asked for C# here
but not for C++ which will be slightly different.
I tried directly initialize using the string, but that failed. I also tried .Split but that produces strings. I also dont want to do any complicated streamreader stuff.
The answer in the link must have an equivalent for C++/cli.
As it mentioned in a comments you can use Split to convert the string to an array of strings, then you can use Array::ConvertAll to convert to an array of int values and after manipulating the values you can ise String::Join to convert an array of ints to a single string.
Here's a code sample:
String^ tags = gcnew String("1,3,5,9");
String^ separator = ",";
array<String^>^ tagsArray = tags->Split(separator->ToCharArray());
array<int>^ tagsIntArray = Array::ConvertAll<String^, int>(tagsArray,
gcnew Converter<String^, int>(Int32::Parse));
// Do your stuff
String^ resultString = String::Join<int>(separator, tagsIntArray);
Any idea how i can separate a string with character and numbers, for example
12345ABC678 to make it look like this
1|2|3|4|5|A|B|C|6|7|8??
Or if this is not possile, how can i take this string a put every character or nr of it in a different textBox like this?
You can use String.Join and String.ToCharArray:
string input = "12345ABC678";
string result = String.Join("|", input.ToCharArray());
Instead of ToCharArray(creates a new array) you could also cast the string to IEnumerable<char> to force it to use the right overload of String.Join:
string result = String.Join("|", (IEnumerable<char>)input);
use
String aString = "AaBbCcDd";
var chars = aString.ToCharArray();
Then you can loop over the array (chars)
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