9

I am practicing over the summer to try and get better and I am a little stuck on the following:

http://www.javabat.com/prob/p123384

Given a string, return a new string where the first and last chars have been exchanged.


Examples:

frontBack("code") → "eodc"
frontBack("a") → "a"
frontBack("ab") → "ba"

Code:

public String frontBack(String str) 
{
    String aString = "";
    
    if (str.length() == 0){
        return "";
    }
    
    char beginning = str.charAt(0);
    char end = str.charAt(str.length() - 1);
    
    str.replace(beginning, end);
    str.replace(end, beginning);
    
    return str;
}
Community
  • 1
  • 1

17 Answers17

9

Strings can be split into an array of chars and can be made with an array of chars. For more details on String objects, go to the Java API and click on String in the lower left pane. That pane is sorted alphabetically.

Edit: Since some people are being more thorough, I think I'll give additional details. Create a char array using String's .toCharArray() method. Take the first element and store it in a char, swap the first element with the last, and place the element you stored in a char into the last element into the array, then say:

String temp = new String(charArray);

and return that. This is assuming that charArray is your array of chars.

mnuzzo
  • 3,529
  • 4
  • 26
  • 29
  • +1, this is a good approach as well. The String.toCharArray method can be used to return a char[]. – coobird Jun 22 '09 at 16:26
  • 1
    I think that going over a char array may be overkill for this problem. Why not just do some substrings? – Thorbjørn Ravn Andersen Jun 22 '09 at 16:57
  • I'm not looping over an array, I'm just converting to one, switching the two which need to be switched and converting it back into a String. It uses one fewer method call than the substring technique at its fewest method calls. – mnuzzo Jun 22 '09 at 17:21
7

Rather than using the String.replace method, I'd suggest using the String.substring method to get the characters excluding the first and last letter, then concatenating the beginning and end characters.

Furthermore, the String.replace method will replace all occurrences of the specified character, and returns a new String with the said replacements. Since the return is not picked up in the code above, the String.replace calls really don't do much here.

This is because String in Java is immutable, therefore, the replace method cannot make any changes to the original String, which is the str variable in this case.


Also to add, this approach won't work well with Strings that have a length of 1. Using the approach above, a call to String.substring with the source String having a length of 1 will cause a StringIndexOutOfBoundsException, so that will also have to be taken care of as a special case, if the above approach is taken.

Frankly, the approach presented in indyK1ng's answer, where the char[] is obtained from the String and performing a simple swap of the beginning and end characters, then making a String from the modified char[] is starting to sound much more pleasant.

Community
  • 1
  • 1
coobird
  • 159,216
  • 35
  • 211
  • 226
  • i tried this by creating a new String and assigning the value String newString = str.substring(1, str.length() -2); return end + newString + beginning; but it didnt work –  Jun 22 '09 at 16:27
  • didnt work = wouldn't compile saying illegal start of expression –  Jun 22 '09 at 16:28
  • I tried out what I've written and was able to get the compile the code and make it run correctly. "Illegal start of expression" sounds like a compiler error where some token (such as a semicolon) was added or missing. – coobird Jun 22 '09 at 16:33
4

String instances in Java are immutable. This means that you cannot change the characters in a String; a different sequence of characters requires a new object. So, when you use the replace method, throw away the original string, and use the result of the method instead.

For this method, however, you probably want to convert the String instance to an array of characters (char[]), which are mutable. After swapping the desired characters, create a new String instance with that array.

erickson
  • 265,237
  • 58
  • 395
  • 493
2

A couple of hints:

  • Strings are immutable, meaning they cannot be changed. Hence, str.replace() does not change str, instead it returns a new string.

  • Maybe replace isn't the best... Consider frontBack("abcabc"): your function, if it were corrected, would replace 'a' with 'c' yielding "cbccbc", then 'c' with 'a' yielding "abaaba". That's not quite right!

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
2

The replace method in String actually returns a String, so if you were to insist on using replace, you'd do:

beginReplace = str.replace( beginning, end );
endReplace = beginReplace.replace( end, beginning );
return( str );

But this actually doesn't solve your specific problem, because replace replaces all occurences of a character in the string with its replacement.

For example, if my string was "apple" and I said "apple".replace( 'p', 'q' ), the resulting string would be "aqqle."

FreeMemory
  • 8,444
  • 7
  • 37
  • 49
2

Yet another example without creating additional objects:

if (str.length() > 1) {
    char[] chars = str.toCharArray();
    // replace with swap()
    char first = chars[0];
    chars[0] = chars[chars.length - 1];
    chars[chars.length - 1] = first;
    str = new String(chars);
}

return str;

Edit: Performing the swap on length = 1 string is no-op.

Edit 2: dfa's change to copyValueOf did not make any sense as the Java source says in String.java: "// All public String constructors now copy the data." and the call is just delegated to a string constructor.

akarnokd
  • 69,132
  • 14
  • 157
  • 192
  • additional object: String.toCharArray() creates "a newly allocated character array" which still is an object. – user85421 Jun 22 '09 at 23:10
  • True. An user called dfa added that sentence to my answer and made other changes (see edit2). He should have just post his own answer – akarnokd Jun 23 '09 at 07:07
2

You could use a regex..

return str.replaceFirst("(.)(.*)(.)", "$3$2$1");
rich
  • 989
  • 2
  • 9
  • 17
1

Just another, slightly different, approach, so you get a sense of the spectrum of possibilities. I commend your attention to the quick exit for short strings (instead of nesting the more-complicated processing in an if() clause), and to the use of String.format(), because it's a handy technique to have in your toolbox, not because it's notably better than regular "+" concatenation in this particular example.

public static String exchange(String s) {
    int n = s.length();
    if (n < 2)
        return s;
    return String.format("%s%s%s", s.charAt(n - 1), s.substring(1, n - 1), s.charAt(0));
}
Carl Manaster
  • 39,912
  • 17
  • 102
  • 155
1

Simple solution is:

public String frontBack(String str) {
  if (str == null || str.length() == 0) {
    return str;
  }
  char[] cs = str.toCharArray();
  char first = cs[0];
  cs[0] = cs[cs.length -1];
  cs[cs.length -1] = first;
  return new String(cs);
}

Using a character array (watch out for the nasty empty String or null String argument!)


Another solution uses StringBuilder (which is usually used to do String manupilation since String itself is immutable.

public String frontBack(String str) {
  if (str == null || str.length() == 0) {
    return str;
  }
  StringBuilder sb = new StringBuilder(str);  
  char first = sb.charAt(0);
  sb.setCharAt(0, sb.charAt(sb.length()-1));
  sb.setCharAt(sb.length()-1, first);
  return sb.toString();
}

Yet another approach (more for instruction than actual use) is this one:

public String frontBack(String str) {
  if (str == null || str.length() < 2) {
    return str;
  }
  StringBuilder sb = new StringBuilder(str);
  String sub = sb.substring(1, sb.length() -1);
  return sb.reverse().replace(1, sb.length() -1, sub).toString();
}

Here the complete string is reversed and then the part that should not be reversed is replaced with the substring. ;)

Maarten Winkels
  • 2,407
  • 16
  • 15
0
public String frontBack(String input)
{
    return
        input.substring(input.length() - 1) +  // The last character
        input.substring(1, input.length() - 1) +  // plus the middle part
        input.substring(0, 1);                  // plus the first character.
}
oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
Daniel Brückner
  • 59,031
  • 16
  • 99
  • 143
0

You can use a StringBuilder that represents "a mutable sequence of characters".
It has all methods needed to solve the problem: charAt, setCharAt, length and toString.

oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
user85421
  • 28,957
  • 10
  • 64
  • 87
0
if (s.length < 2) {
   return s;
}
return s.subString(s.length - 1) + s.subString(1, s.length - 2) + s.subString(0, 1);

(untested, indexes may be of by one...

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
0
public String lastChars(String a, String b) {

  if(a.length()>=1&&b.length()>=1){
   String str = a.substring(0,1);
    String str1 =b.substring(b.length()-1);
    return str+str1;
}
else if(a.length()==0&&b.length()==0){
 String v ="@";
String z ="@";
return v+z;
   }
   else if(a.length()==0&&b.length()>=1){

   String s ="@";
   String s1 = b.substring(b.length()-1);
   return s+s1;
   }
   else if(a.length()>=1&&b.length()==0){
   String f= a.substring(0,1);
   String h = "@";
   return f+h;
   }
   return a;
   }
0

You can use this code:

public String frontBack(String str) {
    if (str.length() <= 1) 
        return str;

    String mid = str.substring(1, str.length()-1);

    // last + mid + first
    return str.charAt(str.length()-1) + mid + str.charAt(0);
}
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
-1
class swap 
{
public static void main(String[] args) 
{
    Scanner s=new Scanner(System.in);
    System.out.println("no of elements in array");
    int n=s.nextInt();
    int a[]=new int[n];
    System.out.println("Elements");
    for(int i=0;i<n;i++)
    {
        a[i]=s.nextInt();
    }
    int b[]=new int[n];
    for(int i=0;i<n;i++)
    {
        b[i]=a[i];
    }
    int end=n-1;
    b[0]=b[end];
    b[end]=a[0];
    for(int i=0;i<n;i++)
    {
        System.out.println(b[i]);
    }   
}
}
Sindusha
  • 1
  • 1
-1
if (str.length() <= 1) {
  return str;
}

String mid = str.substring(1, str.length()-1);
return str.charAt(str.length()-1) + mid + str.charAt(0);
Jules Dupont
  • 7,259
  • 7
  • 39
  • 39
-5
    function frontBack(str: string) { 


         return str.slice(str.length - 1) + str.slice(1, -1) + str.slice(0, 1) 

    }

Slice will "cut out" the last letter. Counting the length of the string which is str.length -1, (plus) the reminder sliced string which starts at index 1 and is the last character which expressed at index -1, (plus) sliced last letter which is at index 0 through index 1.

Sam
  • 2,856
  • 3
  • 18
  • 29
  • This does not look like Java. `str: string` instead of `String string`? And `str.slice` is not a standard method for Java strings. – Cecilia Sep 05 '17 at 22:25
  • 1
    This is Java**Script**. The question is about **Java**. On top of that, you're answering a question asked 8 **years** ago, which already had an accepted solution. Please try to avoid 'bumping' old questions, unless you found a new and markedly improved solution to the problem. Also remember to provide some [**context surrounding your code**](https://meta.stackexchange.com/questions/114762) to help explain it. Check out the documentation on [**writing great answers**](http://stackoverflow.com/help/how-to-answer) for some tips on how to make your answers count :) – Obsidian Age Sep 05 '17 at 22:37