Get the last three chars from any string - Java - java

I'm trying to take the last three chracters of any string and save it as another String variable. I'm having some tough time with my thought process.
String word = "onetwotwoone"
int length = word.length();
String new_word = id.getChars(length-3, length, buffer, index);
I don't know how to use the getChars method when it comes to buffer or index. Eclipse is making me have those in there. Any suggestions?

Why not just String substr = word.substring(word.length() - 3)?
Update
Please make sure you check that the String is at least 3 characters long before calling substring():
if (word.length() == 3) {
return word;
} else if (word.length() > 3) {
return word.substring(word.length() - 3);
} else {
// whatever is appropriate in this case
throw new IllegalArgumentException("word has fewer than 3 characters!");
}

I would consider right method from StringUtils class from Apache Commons Lang:
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#right(java.lang.String,%20int)
It is safe. You will not get NullPointerException or StringIndexOutOfBoundsException.
Example usage:
StringUtils.right("abcdef", 3)
You can find more examples under the above link.

Here's some terse code that does the job using regex:
String last3 = str.replaceAll(".*?(.?.?.?)?$", "$1");
This code returns up to 3; if there are less than 3 it just returns the string.
This is how to do it safely without regex in one line:
String last3 = str == null || str.length() < 3 ?
str : str.substring(str.length() - 3);
By "safely", I mean without throwing an exception if the string is nulls or shorter than 3 characters (all the other answers are not "safe").
The above code is identical in effect to this code, if you prefer a more verbose, but potentially easier-to-read form:
String last3;
if (str == null || str.length() < 3) {
last3 = str;
} else {
last3 = str.substring(str.length() - 3);
}

String newString = originalString.substring(originalString.length()-3);

public String getLastThree(String myString) {
if(myString.length() > 3)
return myString.substring(myString.length()-3);
else
return myString;
}

If you want the String composed of the last three characters, you can use substring(int):
String new_word = word.substring(word.length() - 3);
If you actually want them as a character array, you should write
char[] buffer = new char[3];
int length = word.length();
word.getChars(length - 3, length, buffer, 0);
The first two arguments to getChars denote the portion of the string you want to extract. The third argument is the array into which that portion will be put. And the last argument gives the position in the buffer where the operation starts.
If the string has less than three characters, you'll get an exception in either of the above cases, so you might want to check for that.

Here is a method I use to get the last xx of a string:
public static String takeLast(String value, int count) {
if (value == null || value.trim().length() == 0 || count < 1) {
return "";
}
if (value.length() > count) {
return value.substring(value.length() - count);
} else {
return value;
}
}
Then use it like so:
String testStr = "this is a test string";
String last1 = takeLast(testStr, 1); //Output: g
String last4 = takeLast(testStr, 4); //Output: ring

This method would be helpful :
String rightPart(String text,int length)
{
if (text.length()<length) return text;
String raw = "";
for (int i = 1; i <= length; i++) {
raw += text.toCharArray()[text.length()-i];
}
return new StringBuilder(raw).reverse().toString();
}

The getChars string method does not return a value, instead it dumps its result into your buffer (or destination) array. The index parameter describes the start offset in your destination array.
Try this link for a more verbose description of the getChars method.
I agree with the others on this, I think substring would be a better way to handle what you're trying to accomplish.

You can use a substring
String word = "onetwotwoone"
int lenght = word.length(); //Note this should be function.
String numbers = word.substring(word.length() - 3);

Alternative way for "insufficient string length or null" save:
String numbers = defaultValue();
try{
numbers = word.substring(word.length() - 3);
} catch(Exception e) {
System.out.println("Insufficient String length");
}

This method will return the x amount of characters from the end.
public static String lastXChars(String v, int x) {
return v.length() <= x ? v : v.substring(v.length() - x);
}
//usage
System.out.println(lastXChars("stackoverflow", 4)); // flow

Related

How to use recursion to create a searies of substrings in java

So, the task is to create a string that makes a progression throughout the letters of a string, returning a substring progressively longer.
For example if the input is Book, the answer would be: BBoBooBook . For the input Soup the method would return SSoSouSoup. I want to write it recursively. In my current method I receive no error but at the same time no anwer from the compiler.
public static String stringProgression(String str) {
int index = 1;
String result = "";
if (str.length() == 0) {
return "" ;
} else while (index <= str.length()); {
result = result + stringExplosion(str.substring(0, index));
index++;
}
return result;
}
In your code, you are using two different method names, stringProgression and stringExplosion.
Further, you have a while loop with a semicolon, while (index <= str.length()); which forms an empty loop. Since index doesn’t change in this empty loop, it will be an infinite loop when the condition is fulfilled.
Generally, a while loop contradicts the intent to have a recursive solution.
To find a recursive solution to a problem, you have to find the self-similarity in it. I.e. when you look at the intended result for Book, BBoBooBook, you can recognize that the beginning, BBoBoo is the right result for the string Boo, and BBo is the right result for Bo. So, the original string has to be appended to the result of a recursive evaluation of the substring:
public static String stringProgression(String str) {
if(str.isEmpty()) {
return str;
}
return stringProgression(str.substring(0, str.length() - 1)) + str;
}
An alternative, shorter syntax for the same is:
public static String stringProgression(String str) {
return str.isEmpty()? str: stringProgression(str.substring(0, str.length() - 1)) + str;
}
Check this one:
private static String doStringProgression(String str, String res, int length) {
if(length > str.length()) {
return res;
}
return doStringProgression(str, res + str.substring(0, length), length + 1);
}
And you can call the method with input like in the following example:
public static String stringProgression(String str) {
return doStringProgression(str, "", 1);
}

how do i iterate through a string of characters to find a specific character?

I am having a hard time figuring out why my code will not work. I am trying to stop the output on a specific letter, but it keeps iterating through the entire string instead. This is what I have,
public static char stringIterator(String string) {
System.out.println(string);//Keep this line
char lastChar = string.charAt(string.length() - 1);
if (lastChar == 'M') {
return lastChar;
}
else if (string.length() == 1) {
return lastChar;
}
else {
return stringIterator(string.substring(0, string.length() - 2));
}
}
if you want to just see if it has it then you would use
string.contains('char');
if you want to traverse/iterate then
for( int i = 0; i < string.length(); i++)
if(string.at(i) == '#')
{ //whatever you want here
}
You might be over-thinking this...
Java has very good resources for dealing with Strings, check out the docs:
Java String Documentation
if (string.contains('m')){
//dostuff
}
if (string.endsWith('m')){
//dostuff
}
etc.
As for your iteration problem, you'll have to post the rest of your code, as it looks like your Loop is Calling stringIterator(String) from somewhere outside this method.
(It's not really a stringIterator if it doesn't iterate anything)
Also this last line of code:
return stringIterator(string.substring(0, string.length() - 2));
Is recursive (calls itself)... which can cause you trouble. There's certainly uses for recursion, finding something in a 1d array is not one of those uses. Assuming your loop is working properly this could be what's preventing you from stopping the output.
public String substring(int begIndex, int endIndex) - returns a new string that is a substring of the string
Parameters :
beginIndex : the begin index, inclusive.
endIndex : the end index, exclusive.
(eg): String string = "NAME"
string.substring(0, string.length() - 2) - returns "NA"
string.substring(0, string.length() - 1) - returns "NAM" . Use this, thus you will be able to subtract the last character of the string.
Iterative approach
public static char stringIterator(String string) {
char lastChar = string.charAt(0);
for(int i = string.length()-1 ;i>=0;i--) {
System.out.println(string);//Keep this line
lastChar = string.charAt(i);
if (string.length() == 1 || lastChar == 'M') {
break;
} else {
string = string.substring(0, i);
}
}
return lastChar;
}

Cut Java String at a number of character

I would like to cut a Java String when this String length is > 50, and add "..." at the end of the string.
Example :
I have the following Java String :
String str = "abcdefghijklmnopqrtuvwxyz";
I would like to cut the String at length = 8 :
Result must be:
String strOut = "abcdefgh..."
Use substring and concatenate:
if(str.length() > 50)
strOut = str.substring(0,7) + "...";
StringUtils.abbreviate("abcdefg", 6);
This will give you the following result: abc...
Where 6 is the needed length, and "abcdefg" is the string that needs to be abbrevieted.
Use substring
String strOut = "abcdefghijklmnopqrtuvwxyz"
String result = strOut.substring(0, 8) + "...";// count start in 0 and 8 is excluded
System.out.pritnln(result);
Note: substring(int first, int second) takes two parameters. The first is inclusive and the second is exclusive.
Jakarta Commons StringUtils.abbreviate(). If, for some reason you don't want to use a 3rd-party library, at least copy the source code.
One big benefit of this over the other answers to date is that it won't throw if you pass in a null.
You can use safe substring:
org.apache.commons.lang3.StringUtils.substring(str, 0, LENGTH);
You can use String#substring()
if(str != null && str.length() > 8) {
return str.substring(0, 8) + "...";
} else {
return str;
}
You could however make a function where you pass the maximum number of characters that can be displayed. The ellipsis would then cut in only if the width specified isn't enough for the string.
public String getShortString(String input, int width) {
if(str != null && str.length() > width) {
return str.substring(0, width - 3) + "...";
} else {
return str;
}
}
// abcdefgh...
System.out.println(getShortString("abcdefghijklmnopqrstuvwxyz", 11));
// abcdefghijk
System.out.println(getShortString("abcdefghijk", 11)); // no need to trim
Something like this may be:
String str = "abcdefghijklmnopqrtuvwxyz";
if (str.length() > 8)
str = str.substring(0, 8) + "...";
String strOut = str.substring(0, 8) + "...";

How to remove the last character from a string?

I want to remove the last character from a string. I've tried doing this:
public String method(String str) {
if (str.charAt(str.length()-1)=='x'){
str = str.replace(str.substring(str.length()-1), "");
return str;
} else{
return str;
}
}
Getting the length of the string - 1 and replacing the last letter with nothing (deleting it), but every time I run the program, it deletes middle letters that are the same as the last letter.
For example, the word is "admirer"; after I run the method, I get "admie." I want it to return the word admire.
replace will replace all instances of a letter. All you need to do is use substring():
public String method(String str) {
if (str != null && str.length() > 0 && str.charAt(str.length() - 1) == 'x') {
str = str.substring(0, str.length() - 1);
}
return str;
}
Why not just one liner?
public static String removeLastChar(String str) {
return removeLastChars(str, 1);
}
public static String removeLastChars(String str, int chars) {
return str.substring(0, str.length() - chars);
}
Full Code
public class Main {
public static void main (String[] args) throws java.lang.Exception {
String s1 = "Remove Last CharacterY";
String s2 = "Remove Last Character2";
System.out.println("After removing s1==" + removeLastChar(s1) + "==");
System.out.println("After removing s2==" + removeLastChar(s2) + "==");
}
public static String removeLastChar(String str) {
return removeLastChars(str, 1);
}
public static String removeLastChars(String str, int chars) {
return str.substring(0, str.length() - chars);
}
}
Demo
Since we're on a subject, one can use regular expressions too
"aaabcd".replaceFirst(".$",""); //=> aaabc
The described problem and proposed solutions sometimes relate to removing separators. If this is your case, then have a look at Apache Commons StringUtils, it has a method called removeEnd which is very elegant.
Example:
StringUtils.removeEnd("string 1|string 2|string 3|", "|");
Would result in:
"string 1|string 2|string 3"
public String removeLastChar(String s) {
if (s == null || s.length() == 0) {
return s;
}
return s.substring(0, s.length()-1);
}
Don't try to reinvent the wheel, while others have already written libraries to perform string manipulation:
org.apache.commons.lang3.StringUtils.chop()
In Kotlin you can used dropLast() method of the string class.
It will drop the given number from string, return a new string
var string1 = "Some Text"
string1 = string1.dropLast(1)
Use this:
if(string.endsWith("x")) {
string= string.substring(0, string.length() - 1);
}
if (str.endsWith("x")) {
return str.substring(0, str.length() - 1);
}
return str;
For example, the word is "admirer"; after I run the method, I get "admie." I want it to return the word admire.
In case you're trying to stem English words
Stemming is the process for reducing inflected (or sometimes derived) words to their stem, base or root form—generally a written word form.
...
A stemmer for English, for example, should identify the string "cats" (and possibly "catlike", "catty" etc.) as based on the root "cat", and "stemmer", "stemming", "stemmed" as based on "stem". A stemming algorithm reduces the words "fishing", "fished", "fish", and "fisher" to the root word, "fish".
Difference between Lucene stemmers: EnglishStemmer, PorterStemmer, LovinsStemmer outlines some Java options.
As far as the readability is concerned, I find this to be the most concise
StringUtils.substring("string", 0, -1);
The negative indexes can be used in Apache's StringUtils utility.
All negative numbers are treated from offset from the end of the string.
string = string.substring(0, (string.length() - 1));
I'm using this in my code, it's easy and simple.
it only works while the String is > 0.
I have it connected to a button and inside the following if statement
if (string.length() > 0) {
string = string.substring(0, (string.length() - 1));
}
public String removeLastChar(String s) {
if (!Util.isEmpty(s)) {
s = s.substring(0, s.length()-1);
}
return s;
}
removes last occurence of the 'xxx':
System.out.println("aaa xxx aaa xxx ".replaceAll("xxx([^xxx]*)$", "$1"));
removes last occurrence of the 'xxx' if it is last:
System.out.println("aaa xxx aaa ".replaceAll("xxx\\s*$", ""));
you can replace the 'xxx' on what you want but watch out on special chars
Look to StringBuilder Class :
StringBuilder sb=new StringBuilder("toto,");
System.out.println(sb.deleteCharAt(sb.length()-1));//display "toto"
// creating StringBuilder
StringBuilder builder = new StringBuilder(requestString);
// removing last character from String
builder.deleteCharAt(requestString.length() - 1);
How can a simple task be made complicated. My solution is:
public String removeLastChar(String s) {
return s[0..-1]
}
or
public String removeLastChar(String s) {
if (s.length() > 0) {
return s[0..-1]
}
return s
}
// Remove n last characters
// System.out.println(removeLast("Hello!!!333",3));
public String removeLast(String mes, int n) {
return mes != null && !mes.isEmpty() && mes.length()>n
? mes.substring(0, mes.length()-n): mes;
}
// Leave substring before character/string
// System.out.println(leaveBeforeChar("Hello!!!123", "1"));
public String leaveBeforeChar(String mes, String last) {
return mes != null && !mes.isEmpty() && mes.lastIndexOf(last)!=-1
? mes.substring(0, mes.lastIndexOf(last)): mes;
}
A one-liner answer (just a funny alternative - do not try this at home, and great answers already given):
public String removeLastChar(String s){return (s != null && s.length() != 0) ? s.substring(0, s.length() - 1): s;}
Most answers here forgot about surrogate pairs.
For instance, the character 𝕫 (codepoint U+1D56B) does not fit into a single char, so in order to be represented, it must form a surrogate pair of two chars.
If one simply applies the currently accepted answer (using str.substring(0, str.length() - 1), one splices the surrogate pair, leading to unexpected results.
One should also include a check whether the last character is a surrogate pair:
public static String removeLastChar(String str) {
Objects.requireNonNull(str, "The string should not be null");
if (str.isEmpty()) {
return str;
}
char lastChar = str.charAt(str.length() - 1);
int cut = Character.isSurrogate(lastChar) ? 2 : 1;
return str.substring(0, str.length() - cut);
}
Java 8
import java.util.Optional;
public class Test
{
public static void main(String[] args) throws InterruptedException
{
System.out.println(removeLastChar("test-abc"));
}
public static String removeLastChar(String s) {
return Optional.ofNullable(s)
.filter(str -> str.length() != 0)
.map(str -> str.substring(0, str.length() - 1))
.orElse(s);
}
}
Output : test-ab
public String removeLastCharacter(String str){
String result = null;
if ((str != null) && (str.length() > 0)) {
return str.substring(0, str.length() - 1);
}
else{
return "";
}
}
if we want to remove file extension of the given file,
** Sample code
public static String removeNCharactersFromLast(String str,int n){
if (str != null && (str.length() > 0)) {
return str.substring(0, str.length() - n);
}
return "";
}
For kotlin check out
string.dropLast(1)
if you have special character like ; in json just use String.replace(";", "") otherwise you must rewrite all character in string minus the last.
Why not use the escape sequence ... !
System.out.println(str + '\b');
Life is much easier now . XD ! ~ A readable one-liner
How to make the char in the recursion at the end:
public static String removeChar(String word, char charToRemove)
{
String char_toremove=Character.toString(charToRemove);
for(int i = 0; i < word.length(); i++)
{
if(word.charAt(i) == charToRemove)
{
String newWord = word.substring(0, i) + word.substring(i + 1);
return removeChar(newWord,charToRemove);
}
}
System.out.println(word);
return word;
}
for exemple:
removeChar ("hello world, let's go!",'l') → "heo word, et's go!llll"
removeChar("you should not go",'o') → "yu shuld nt goooo"
Here's an answer that works with codepoints outside of the Basic Multilingual Plane (Java 8+).
Using streams:
public String method(String str) {
return str.codePoints()
.limit(str.codePoints().count() - 1)
.mapToObj(i->new String(Character.toChars(i)))
.collect(Collectors.joining());
}
More efficient maybe:
public String method(String str) {
return str.isEmpty()? "": str.substring(0, str.length() - Character.charCount(str.codePointBefore(str.length())));
}
just replace the condition of "if" like this:
if(a.substring(a.length()-1).equals("x"))'
this will do the trick for you.
Suppose total length of my string=24
I want to cut last character after position 14 to end, mean I want starting 14 to be there.
So I apply following solution.
String date = "2019-07-31T22:00:00.000Z";
String result = date.substring(0, date.length() - 14);
I had to write code for a similar problem. One way that I was able to solve it used a recursive method of coding.
static String removeChar(String word, char charToRemove)
{
for(int i = 0; i < word.lenght(); i++)
{
if(word.charAt(i) == charToRemove)
{
String newWord = word.substring(0, i) + word.substring(i + 1);
return removeChar(newWord, charToRemove);
}
}
return word;
}
Most of the code I've seen on this topic doesn't use recursion so hopefully I can help you or someone who has the same problem.

How can I exchange the first and last characters of a string in Java?

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;
}
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.
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.
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.
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!
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."
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.
You could use a regex..
return str.replaceFirst("(.)(.*)(.)", "$3$2$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));
}
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. ;)
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...
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.
}
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.
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;
}
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);
}
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]);
}
}
}
if (str.length() <= 1) {
return str;
}
String mid = str.substring(1, str.length()-1);
return str.charAt(str.length()-1) + mid + str.charAt(0);
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.

Categories

Resources