+ 1
I'm newbie in java... Can anyone help me to solve this problem.
There are 2 student names James Paul and John Will. A program that will exchange the last name of the two students in such a way that the new names are going to be James Will and John Paul Input: 2 strings S1 = "James Paul" S2 = "John Will" Output: James Will John Paul Note : No split() should be used.
3 Answers
+ 2
Your task says two Strings as input.
In this case you can work with indexOf() and substring()
s1.indexOf(" ") returns the index of the space: 5
s2.indexOf(" ") returns 4
(index starts at 0)
int index1 = s1.indexOf(" ");
int index2 = s2.indexOf(" ");
substring(int startIndex, int endIndex) returns a string from startIndex to endIndex -1 (excluding endIndex)
substring(int index) returns a substring which starts at the index and end at the end of this string
s1.substring(0, index1) returns "James"
s2.substring(index2) returns
" Will" (with the space)
Now put theese two strings together:
-> String swapped1 = s1.substring(0, index1) + s2.substring(index2);
-> "James Will"
Same for second name:
-> String swapped2 =
s2.substring(0, index2) + s1.substring(index1);
-> "John Paul"
+ 2
Read inputs by next() method into first name, last name sequentially.. Then swap last names...
Edit:
Give a reply, if it not enough...
+ 1
Thanks.. I got it.