如何在 Java 中大写字符串的首字母

本教程文章将介绍如何使用 Java 将字符串的首字母大写。有一些常用的方法用于将给定 string 值的第一个字母转换为大写。不同的方法有 upperCaseFirst()toCharArray()toUpperCase()appendTail() 方法,String.substring() 方法和 capitalize() 函数与 String.substring() 方法。让我们通过实例来讨论每个方法的实现。

使用 upperCaseFirst()toCharArray() 方法相关联的字符串首字母大写

在这个过程中,我们引入了 upperCaseFirst() 方法,该方法接收一个字符串值并将其转换为一个字符数组。然后,我们使用 Character 类和 toUpperCase() 方法对字符数组中的第一个元素进行大写。最后,我们使用 String 构造函数将更新后的字符数组转换为字符串。让我们按照下面的例子进行操作。

import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
  public static String upperCaseFirst(String val) {
      char[] arr = val.toCharArray();
      arr[0] = Character.toUpperCase(arr[0]);
      return new String(arr);
   }
    public static void main(String[] args) {
        String val1 = "java";
        String val2 = "advanced java";
        String output = upperCaseFirst(val1);
        System.out.println(val1);
        System.out.println(output);
        output = upperCaseFirst(val2);
        System.out.println(val2);
        System.out.println(output);
    }
}

输出:

java
Java
advanced java
Advanced java

使用 toUpperCase()appendTail() 方法将字符串的首字母大写

在输出时,有两个不同的方法出现,即 toUpperCase()appendTail()。为了在一个应用程序中实现这两个方法,需要导入 regex.Matcherregex.Pattern 包。下面的例子将详细解释这些方法。

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
  public static void main(String[] args) {
      String str = "hello world!";
      System.out.println(str);
      StringBuffer strbf = new StringBuffer();
      Matcher match = Pattern.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(str);
      while(match.find())
      {
         match.appendReplacement(strbf, match.group(1).toUpperCase() + match.group(2).toLowerCase());
      }
      System.out.println(match.appendTail(strbf).toString())
  }
}

输出:

hello world!
Hello World!

使用 String.substring()将字符串的首字母大写

最简单和最容易的技巧是使用 String.substring() 方法来大给定字符串的首字母。让我们通过下面的例子来进行介绍。

import java.util.*;
public class Main {
    public static void main(String[] args) {
        String str = "java";
        String firstLtr = str.substring(0, 1);
        String restLtrs = str.substring(1, str.length());
        firstLtr = firstLtr.toUpperCase();
        str = firstLtr + restLtrs;
        System.out.println("The modified string is: "+str);
    }
}

输出:

The modified string is: Java

在上面的例子中, 我们创建了一个字符串变量 – str. 然后我们从 str 形成两个子字符串,其中 firstLtr 代表字符串的第一个字母,restLtrs 代表字符串的剩余字母。在结尾部分,我们使用 toUpperCase() 方法将 firstLtr 转换为大写,并将两个子字符串连接起来形成字符串本身。

使用 String.substring() 方法用函数 capitalize() 将字符串的首字母大写

在最后一个例子中,我们将使用 capitalize() 函数来确保给定的字符串在使用 String.substring() 方法之前至少有一个字符。

import java.util.*;
public class Main {
    public static String capitalize(String str){
      if(str == null || str.isEmpty()) {
          return str;
      }
      return str.substring(0, 1).toUpperCase() + str.substring(1);
    }
    public static void main(String[] args) {
        String str = "hello world!";
        String firstLtr = str.substring(0, 1);
        String restLtrs = str.substring(1, str.length());
        firstLtr = firstLtr.toUpperCase();
        str = firstLtr + restLtrs;
        System.out.println("The modified string is: "+str);
    }
}

输出:

The modified string is: Hello world!

如何在 JavaScript 中大写字符串首字母

在 JavaScript 中,有很多方法可以将字符串的第一个字母大写。

比如说

  • "this is an example" -> "This is an example"
  • "the Atlantic Ocean" -> "The Atlantic Ocean"

使用 toUpperCase()slice() 方法来实现 JavaScript 中字符串首字母大写

toUpperCase() 方法将一个字符串中的所有字母转换为大写字母;我们将结合其他 JavaScript 函数使用它来达到我们想要的目标。

slice(start,end) 方法提取一个字符串的一部分,并将其作为一个新的字符串返回。

start 是必要的参数。它是开始分片字符串的位置。

end 是可选参数。它是结束分片字符串的位置。如果省略,slice() 将在字符串的末端结束。

例子: slice() 在字符串的结尾处结束

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body style = "text-align:center;">
        <input id = "input" type="text" name="input"/>
        <button onclick="capitalizeString()">
            Capitalize
        </button>
        <h3 id = "modified-string" >
        </h3>
        <script>
        function capitalizeString() {
          let input = document.getElementById("input");
          let headingElement = document.getElementById("modified-string");
          let string = input.value;
          headingElement.innerHTML = string[0].toUpperCase() +
            string.slice(1);
        }
        </script>
    </body>
</html>

输出:

如何在 JavaScript 中大写字符串首字母

另一个例子

//shortened version
function capitalize(sentence)
{
    return sentence && sentence[0].toUpperCase() + sentence.slice(1);
}

使用 toUpperCase()charAt() 来实现 JavaScript 中字符串首字母大写

charAt() 方法从字符串的指定索引中返回字符。索引从 0 开始。

例子:

//We will use the same html above
function capitalizeString() {
     let input = document.getElementById("input");
     let headingElement = document.getElementById("modified-string");
     let string = input.value;
     headingElement.innerHTML = string.charAt(0).toUpperCase() +
         string.slice(1); ;
 }

使用 toUpperCase()replace() 来实现 JavaScript 中字符串首字母大写

replace() 是 JavaScript 中的一个内置方法,它可以根据指定的值或正则表达式模式搜索给定的字符串,替换它,并返回一个新的字符串。

JavaScript replace() 语法

string.replace(paramA, paramB)

这里,paramA 是一个值或正则表达式,paramB 是一个用来替换 paramA 的值。

注意
原始字符串将保持不变,返回值是一个包含替换项的新字符串。

replace() 方法的简单示例

function replaceFunction() {
  let str = "Google Event";
  let res = str.replace("Google", "Microsoft");
  console.log(res)
}
replaceFunction();
function replaceAllFunction() {
  let str = "Google Event will be in Headquarters of Google";
  let res = str.replace(/Google/g, "Microsoft");
  console.log(res)
}
replaceFunction();
注意
replace() 方法默认只替换第一个实例。我们应该使用正则表达式全局(g)修饰符来替换所有出现的实例。

例:

//We will use the same html above
function capitalizeString() {
    let input = document.getElementById("input");
    let headingElement = document.getElementById("modified-string");
    let string = input.value;
    headingElement.innerHTML = string.replace(/^./, string[0].toUpperCase());
}

/^./代表字符串的第一个字母。在 RegExp 教程 和 RegExp Object 参考 阅读更多关于正则表达式的内容。