Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalize last letter of a string

How can I capitalize only the last letter of a string.

For example:

hello

becomes:

hellO
like image 679
Kathy Avatar asked Jul 26 '11 00:07

Kathy


People also ask

How do you capitalize the last letter of a string in python?

If you just want the last letter of the last word, str. capitalize() is the way to go.

How do you capitalize the first and last letter of a string?

To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it. Now, we would get the remaining characters of the string using the slice() function.

How do you capitalize an entire string?

Performing the . upper() method on a string converts all of the characters to uppercase, whereas the lower() method converts all of the characters to lowercase.

How do you capitalize the first letter of each word in a string in python?

Python String capitalize() Method Syntax Return: The capitalize() function returns a string with the first character in the capital.


3 Answers

Convoluted but fun:

echo strrev(ucfirst(strrev("hello")));

Demo: http://ideone.com/7QK5B

as a function:

function uclast($str) {
    return strrev(ucfirst(strrev($str)));
}
like image 64
karim79 Avatar answered Oct 14 '22 00:10

karim79


When $s is your string (Demo):

$s[-1] = strtoupper($s[-1]);

Or in form of a function:

function uclast(string $s): string
{
  $s[-1] = strtoupper($s[-1]);
  return $s;
}

And for your extended needs to have everything lower-case except the last character explicitly upper-case:

function uclast(string $s): string
{
  if ("" === $s) {
    return $s;
  }

  $s = strtolower($s);
  $s[-1] = strtoupper($s[-1]);

  return $s;
}
like image 44
hakre Avatar answered Oct 14 '22 00:10

hakre


There are two parts to this. First, you need to know how to get parts of strings. For that, you need the substr() function.

Next, there is a function for capitalizing a string called strtotupper().

$thestring="Testing testing 3 2 1. aaaa";
echo substr($thestring, 0, strlen($thestring)-2) . strtoupper(substr($thestring, -1));
like image 1
Brad Avatar answered Oct 14 '22 01:10

Brad