简体   繁体   中英

Capitalizing first and last letter in java using String methods

I'm a beginner in java and we were asked to that will capitalize the first and last letter of the word.

[Hint: Capture the letter as a string (using the substring method) then use the toUpperCase() method.]

all i have so far is this,

import java.util.Scanner;

public class Excercise6 {
   public static void main (String [] args){

    Scanner keyboard = new Scanner (System.in);
    System.out.print("Please Type a word: ");
    String word = keyboard.nextLine();

    int stringLength = word.length();
   String letter1 = word.substring (0,1);
   String lastletter = word.substring ((stringLength-1),(stringLength));
   String newWord =letter1.toUpperCase() + lastletter.toUpperCase();


    System.out.println("The word with first letter capitalized is: " + newWord );

   }
}

How do I add the words between the first and the last letter??

Code looks fine, just make some changes

String newWord = letter1.toUpperCase()
                + word.substring(1, word.length() - 1)
                + lastletter.toUpperCase();

First Letter - letter1.toUpperCase()

Middle String - word.substring(1, word.length() - 1)

Last Letter - lastletter.toUpperCase();

output

Please Type a word: ankur
The word with first letter capitalized is: AnkuR

Try something like this:

String a = "java";
String first = a.substring(0, 1).toUpperCase();
String last = a.substring((a.length() - 1), a.length()).toUpperCase();
String middle = a.substring(1, a.length() - 1);
System.out.println(first + middle + last);

You could try the following

String letter1 = word.substring (0,1);
String lastletter = word.substring ((stringLength-1),(stringLength));
String newWord =letter1.toUpperCase() + word.subString(1, stringLength-1) + lastletter.toUpperCase();

That should give you the "middle" of the word, without the first and last letters

The String. substring() method will give you a substring. So split the word into parts like you've partially did:-

String startChar = word.substring(0, 1);
String endChar = word.substring(word.length()-1); //If you leave out the last argument, it goes all the way to the end of the String
String middle = word.substring(1, word.length()-1);

Then just build your new word (first character, plus middle section, plus last character) and convert the relevant parts ot upper case with the String. upperCase() method

 String newWord = startChar.toUpperCase() + middle + endChar.toUpperCase();

You can simply do

String st="singhakash";
System.out.println(st.substring(0,1).toUpperCase()+st.substring(1,st.length()-1)+st.substring(st.length()-1).toUpperCase());

Output

SinghakasH

DEMO

Since everybody is giving a suggestion that would work; I'm tuning in on a suggestion that would be more efficient and secure.

String word = keyboard.nextLine();

This does not guarantee a word. It returns a line, which means anything before a newline character '\\n'.

To get the words, you should use:

String[] words = keyboard.nextLine().split(new char[] { ' ', '\t', '\r' });

This will split the line on the characters: space, tab and carriage return (NOTE: not newline).

Next we need to loop through each word with a for-each loop:

for(String word : words)
{
int wordLength = word.length(); // Get length, because we're gonna use       it multiple times
if(wordLength > 0) // Ignore empty words
{
    // Only get the first character and convert it to uppercase (better than using substring)
    // Also note that we don't have to check if there's a character at 0, because we already did with wordLength > 0
    char firstCharacter = Character.toUpperCase(word.charAt(0)); 

    StringBuilder builder = new StringBuilder(firstCharacter); // We use StringBuilder class because it is efficient in concatenating objects to a string

    if(wordLength == 2) // We only got 2 characters, so no inbetween
    {
        char lastCharacter = Character.toUpperCase(word.charAt(1)); // We know this character is at index 1

        builder.append(lastCharacter); // Append last character
    }
    else // More than 2
    {
        String inbetweenCharacters = word.substring(1, wordLength - 2); // Get the words in between using substring
        char lastCharacter = Character.toUpperCase(word.charAt(wordLength - 1)); // Get the last character

        builder.append(inbetweenCharacters); // Append inbetween characters
        builder.append(lastCharacter); // Append last character
    }

    System.out.println(builder.toString()); // Print complete converted word
}
}

I did this on the top of my head, I hope it doesn't have any typos

/** code to add the words of string sentence 1st to last , 2nd to 2ndlast, 3rd to 3rdlast and as on author : deependra singh patel*/

import java.util.Scanner;

public class ReverseStringWordConcate {

  public static void main(String[] args) {
    Scanner scn = new Scanner(System.in);
    System.out.println("Enter The Sentence");
    String s1 = scn.nextLine();
    String []s2 = s1.split(" ");
    int i1 = 0;
    for(int i =s2.length-1;i>=0;i--) {
        if(s2[i]==s2[i1] ){
            char [] arr = s2[i].toCharArray();
            System.out.print(arr.length+s2[i1]);
            break;
        }
        else {
        //System.out.print(s2[i]+s2[i1]+" ");
        char [] arr = s2[i].toCharArray();
        char arr1[] = s2[i1].toCharArray();
        System.out.print((arr.length+arr1.length)+s2[i]+s2[i1]+" ");

        }
        i1++;
}






}
}

/* sample input : deependra singh patel thegun singhraur

   expected output :18singhraurdeependra 11thegunsingh 5patel       

*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM