-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFrontBack.java
More file actions
29 lines (25 loc) · 682 Bytes
/
FrontBack.java
File metadata and controls
29 lines (25 loc) · 682 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
* Given a string, return a new string where the first and last chars have been exchanged.
* frontBack("code") → "eodc"
* frontBack("a") → "a"
* frontBack("ab") → "ba"
*/
public class FrontBack {
//Class for testing and setting dummy values
public static void main( String [] args ) {
//Output tests
System.out.println( frontBack( "Hello World" ) );
}
public static String frontBack( String str ) {
if( str.length() < 1 ) {
return str;
}
else if( str.length() > 1 ) {
char first = str.charAt( 0 );
char last = str.charAt( str.length() - 1 );
return last + str.substring( 1, str.length()-1 ) + first;
} else {
return str;
}
}
}