Last two letters of a user inputted string using substring (Java) - java

I'm writing a program that generates star wars names. The user inputs their first, last, mother's maiden name, birth city, and first car and the program gives a star wars name. I need the last two characters* of the user inputted last name. I know I can use substring, but I cannot get anything to work. The best I have is:
lastname.substring(lastname.length() -2)
which gives the first two letters of the last name, and not the last. Also, I cannot use lastname.substr(-2) because substr for some reason won't work (not sure why, this would be much easier).
Thanks for any help.
*EDIT: I hope I didn't confuse anyone, I need the last two characters of the last name.
Actually I see my problem now: my original last name variable is
String lastname = console.nextLine().substring(0,2).trim().toUpperCase();
which keeps the first two letters, so the reason I was getting the first two letters was because of this. I understand now. Is there a way to get the last two letters from this same variable?

So if the name was Michael, you just want Micha?
Try:
String trimmedLastName = lastName.substring(0, lastName.length() - 2);
For example:
String lastName = "Michael";
String trimmedLastName = lastName.substring(0, lastName.length() - 2);
System.out.println(trimmedLastName); // prints Micha
The reason mine works and yours doesn't is because the first parameter of substring is where to start. So I start from the first letter, and end on the second last letter (not inclusive).
What yours does is start on the second last letter, and continue on until the end of the string.
However, if you wanted just el from Michael, you could do this:
String lastName = "Michael";
String trimmedLastName = lastName.substring(lastName.length() - 2);
System.out.println(trimmedLastName); // prints el

Try this out,
lastname.substring(lastname.length() -3,lastname.length() -1);

If you need the different ways, here:
StringBuffer myString = new StringBuffer(inputString);
myString.revert();
StringBuffer userInput = new StringBuffer(myString.subString(2));
String result = userInput.revert();
Have a nice day.

Because String is immutable so when you call subString it doesn't change the value of lastname.
I think you should do:
String genName = lastname.subString(lastname.lengh()-2);

lastname.substring(lastname.length() - 2) should return the last 2 letters.
lastname.substring(0, 2) returns the first two.
substring(index) is includive
substring(index1, index2) is inclusive, exclusive respectively.

Related

Java - How to display all substrings in String without using an array

I have a string which is :
1|name|lastname|email|tel \n
2|name|lastname|email|tel \n
I know that I have to use a loop to display all lines but the problem is that in my assignment
I can't use arrays or other classes than String and System.
Also I would like to sort names by ascending order without using sort method or arrays.
Do I have to use compareTo method to compare two names ?
If that's the case, how do I use compareTo method to sort names.
For example, if compareTo returns 1, that means that the name is greater than the other one. In that case how do I manage the return to sort name properly in the string ?
To display all substrings of the string as in the example, you can just go through all characters one by one and store them in a string. Whenever you hit a delimiter (e.g. | or \n), print the last string.
Here's a thread on iterating through characters of a string in Java:
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
If you also need to sort the names in ascending order without an array, you will need to scan the input many times - sorting N strings takes at least N*log(N) steps. If this is a data structure question, PriorityQueue should do the trick for you - insert all substrings and then pop them out in a sorted fashion :)
building on the previous answer by StoneyKeys, since i do not have the privilege to comment, you can use a simple if statement that when the char is a delimiter, System.out.println() your previous scanned string. Then you can reset the string to an empty string in preparation for scanning the next string.
In java, there are special .equals() operators for strings and chars so when you won't be using == to check strings or char. Do look into that. To reset the value of string just assign it a new value. This is because the original variable points at a certain string ie "YHStan", by making it point at "", we are effectively "resetting" the string. ie scannedstr = "";
Please read the code and understand what each line of code does. The sample code and comments is only for your understanding, not a complete solution.
String str ="";
String value = "YH\nStan";
for (int i=0; i <value.length(); i++) {
char c = value.charAt(i);
String strc = Character.toString(c);
//check if its a delimiter, using a string or char .equals(), if it is print it out and reset the string
if (strc.equals("\n")) {
System.out.println(str);
str ="";
continue; // go to next iteration (you can instead use a else if to replace this)
}
//if its not delimiter append to str
str = str +strc;
//this is to show you how the str is changing as we go through the loop.
System.out.println(str);
}
System.out.println(str); //print out final string result
This gives a result of:
Y
YH
YH
S
St
Sta
Stan
Stan

How do I replace more than one char in StringBuilder in Java?

I've got some String, and I'd like to replace some chars in it. Everything was running fine until the String hasn't two or more same chars, the program just replacing the first one, and I'm not able to change the second one.
StringBuilder userTitleBuilder = new StringBuilder(conversedTitle);
while (score>1) {
userLetter = userInput.next().charAt(0);
if (movieTitle.contains(String.valueOf(userLetter))) {
charIndex = movieTitle.indexOf(userLetter);
userTitleBuilder.replace(charIndex,userTitleBuilder.length(), String.valueOf(userLetter));
System.out.println(userTitleBuilder);
} else {
--score;
System.out.println("Wrong\nTries left "+score);
}
}
Here's the explanation of this code:
User from the start the program has a score equals to 10. userLetter it's just a char that will get some letter from the user, then if statement checking if movieTitle variable has char equals to that user just entered, if yes, charIndex will have it position (but it contains only first index, what if in word are more same letters?) now userTitleBuilder replace the chars in string that has that many "_" that movieTitle lenght, it's just covering the title.
*movieTitle and userTitleBuilder has the same value = "CocaCola"
I'd like to not get ready solution. I'd like to have some kind of hint, how do I replace more than one same character in String
A method called String.replace("old","new") can be used.
Follow this doc.

java string matching

All that I am doing in my project is taking two values(that I am reading from two different excel files) and checking how similar they are.! I tried using the pattern and matcher classes which works perfectly fine when both the words are exactly the same (as in organisation and organisation/s). In my data I have say something like (employee and employment), I just need "employ" as the common string between the two, in which case..pattern and matches fails.! I am stuck with this since a week.I have about 700 rows in the first excel file and about 9000 in the other. Each cell value that I am reading into the program using java, I am storing them in two separate variables. Next, i tried using 4 for loops to match word by word and character by character to find only those characters that match between the two.I have pasted the coded for the for loop implementation. Four for loops are like driving me nuts.! Any help in completing this would be greatly appreciated.
String str1 = "Cover for employees of the company";
String str2 = "Employment Agencies ";
String str,strfinal;
String[] count1 = str1.split("\\s+");
String[] count2 = str2.split("\\s+");
char[] count11 = str1.toCharArray();
char[] count22 = str2.toCharArray();
for(int i=0;i<count1.length;i++)
{
for(int j=0;j<count2.length;j++)
{
for(int m=0;m<count1[i].length();m++)
{
for(int n=0;n<count2[j].length();n++)
{
if(count11[m]==count22[n])
{
// please look at the logic that I am looking for to implement
}
}
}
}
}
Expected output: employ
one more concept that I am trying to implement (in order to make my program more efficient) is..
cover ----(compared with) employment. First character itself does not match.Implies go to the next word in the second string. Once all words in the second string are traversed and checked for, go to the next word in the first string and compare this word with all the words in the second string.
Okay.. so this is what I am looking for right now.. Any help will be greatly appreciated.
Thanks!

string index out of range exception

I'm looking for help correcting an exception error for 'string index out of range'. My code is supposed to take two strings as input from the user(string1 and string2) and create new strings that are parts of the originals.
So far I have the following:
modString1 = string1.substring(string1.length() -3, string1.length());
modString2 = string2.substring(0,3);
The above code is supposed to take the last 3 characters of string1 and the first 3 characters of string2. The problem I am having comes when the user inputs a string that is shorter than 3 characters.
I'm wondering if there is a way to check the input and add a character (x for example) if the string is too short?
For example, if the user enters 'A' for the first string it will change the string to 'xxA' and if 'A' is entered for the second string it will change that to 'Axx'?
Put an if statement before your code, checking the length of the string before you process it.
For example:
if(string1.length() < 3) {
// Add characters to the string
}
I'm wondering if there is a way to check the input and add a character (x for example) if the string is too short?
What you are looking for is called padding.
It can be done in a number of ways. The simplest is probably to use an external library such as Apache's StringUtils. You could also write a padding method yourself using a StringBuilder.
Related:
How can I pad a String in Java?
put the validation like below and add the string.
For ex.
if(string1.length()<3){
String op = 'xx';
string1 += op;
}

String addition with int

System.out.println(1+2+"3");
System.out.println("1"+2+3);
output:-
33
123
First case is understood but the second case is not clear.
If we are doing + operation in string then is works as append(concatenation).
So in your first case 1+2+"3" ... 1+2 =3 but when it perform 3+"3" java concate 3 into String 3 that is 33.
and in second example "1"+2+3 ... 2 is append into String "1" that results as 12 and then "12" + 3 so result is = 123.
if the left part is String then it would invoke + operation on string which is append(concatenation) , while in number it is summation
+ is right associative; "1"+2 results in "12", and adding 3 gives "123".
The evaluation happens left to right. First time a string is met all the succeeding values are implicitly cast to string before being added to the expression. So in the first case you have 1+2 = 3, then a string is met and 2 is appended to the string "3". Second case - the string "1" is met and then each int is cast to string before being added to the result accumulated so far.
If you add anything to a string, it will be a string so 1 + "2"(string) is "12"(string).
if you keep on adding to string, you will keep on getting strings "12"(string) + 33 is "1233"(string).
I think this better justify your question.
Thanks
Kapil Garg
well, mathematical expressions are scanned from right usually.
In first case, if you scan from right , u get two int operands(1 and 2) and u add it and it comes to be 3 as int when move on further you find one operand("3") is string so you concatenate it and it comes out to be 33.
In second case, if you scan from right u get one string operand("1") and you concatenate it with 2 so it comes out to be 12 as string, when you move on you find int(2), but this time your first operand(12) is string, so again you concatenate it and it comes out to be 123.
in first case 1+2+"3"
first 1+2 is added and appended with string so output is 33.
but in the second case: "1"+2+3
first string is appended with 2 so operation of "1"+2 is string, automatically last is ("12"+3) also string.
that is :
1st case:
numeric output + string = string
2nd case:
string + numeric = string
that is casting to parent class with lower/wrapper data types the final output would be parent class.

Categories