Given a string array. Write a code to sort the strings in the array based on their 2nd character.
Assumption :- Each array element contains more than one character.
Java1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class SortString { public static void main(String[] args) { String[] arr = { "heist", "code", "blog", "python", "java"}; for(int i=0; i<arr.length-1; i++){ for(int j=i+1; j<arr.length; j++){ if(arr[i].charAt(1)>arr[j].charAt(1)){ String temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } for(String s:arr) System.out.println(s); } } |
Python (using sort and lambda)
arr = [ "heist", "code", "blog", "python", "java" ] arr.sort(key=lambda x:x[1]) print(arr)
Python (without using any method)
arr = [ "heist", "code", "blog", "python", "java" ] for i in range(0, len(arr)): for j in range(i+1,len(arr)): if arr[i][1]>arr[j][1]: arr[i], arr[j] = arr[j], arr[i] print(arr)