Remove the Last Character from a String

How to remove the last character from a string?

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;
}

Delete the last two characters of the String

Subtract -2 or -3 basis of removing last space also.

 public static void main(String[] args) {
String s = "apple car 05";
System.out.println(s.substring(0, s.length() - 2));
}

Output

apple car

Removing last character in C

Just set the last char to be '\0':

str[strlen(str)-1] = '\0';

In C, \0 indicates a string ending.

How can I remove the last character of a sentence in JavaScript?

Since the str.slice function returns the sliced part between two index as a substring, in your case, you should use str.slice(0,-1), that is equals to str.slice(0, str.length - 1). And it means that is going to return every character from zero index without the last character of the string passed.

function morseCode(str) {
morseCode = {
"A": ".- ",
"B": "-... ",
"C": "-.-. ",
"D": "-.. ",
"E": ". ",
"F": "..-. ",
"G": "--. ",
"H": ".... ",
"I": ".. ",
"J": ".--- ",
"K": "-.- ",
"L": ".-.. ",
"M": "-- ",
"N": "-. ",
"O": "--- ",
"P": ".--. ",
"Q": "--.- ",
"R": ".-. ",
"S": "... ",
"T": "- ",
"U": "..- ",
"W": ".-- ",
"X": "-..- ",
"Y": "-.-- ",
"Z": "--.. ",
'1':'.---- ',
'2':'..--- ',
'3':'...-- ',
'4':'....- ',
'5':'..... ',
'6':'-.... ',
'7':'--... ',
'8':'---.. ',
'9':'----. ',}

str = str.replace(/[!,?]/g , '');

str = str.replace(/\s/g, '');

return str.toUpperCase().split("").map(el => {
return morseCode[el] ? morseCode[el] : el;
}).join("").slice(0,-1); // this returns the string without the last character.

};

How to remove first and last character of a string in Rust?

You can use the .chars() iterator and ignore the first and last characters:

fn rem_first_and_last(value: &str) -> &str {
let mut chars = value.chars();
chars.next();
chars.next_back();
chars.as_str()
}

It returns an empty string for zero- or one-sized strings and it will handle multi-byte unicode characters correctly. See it working on the playground.

Remove the last character of each string in array (JavaScript)

use a .map() to get a new array and for each item do a .slice(0,-1) to remove the last char.