Computer Science, asked by tibrewalparth5, 5 hours ago

Write a java statement for each of the following. (i) Extract the second last character of a word stored in the variable w. (ii) Find and display the index of last space in a string s.​

Answers

Answered by BrainlyProgrammer
5

Question:-

  • Write a java statement for each of the following.
  1. Extract the second last character of a word stored in the variable w.
  2. Find and display the index of last space in a string s.

Answer:-

  1. char ch=w.charAt(w.length()-2);
  2. int index= s.lastIndexOf(' ');

Note:-

  • charAt() returns the character at given index.
  • length() returns the length of the string.
  • lastIndexOf() returns the last Index of a given character.

  • Since we have to find the last second character, use length()-2. Note that the word can be of any length.

Sample Example:-

  • Let the word be "BrainlyProgrammer"
  • I want 'e' as the answer how will I get? The length of the word is 17 (length starts with 1 and index starts with 0)
  • Index of 'e' is 15.
  • And character in length()-1 th index is the last character. So, to find second last use length()-2

Similar questions