首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何更改字符串首字母的大小写?

更改字符串首字母的大小写可以通过编程语言的内置函数来实现。以下是几种常见编程语言的实现方法:

  1. Python
代码语言:python
代码运行次数:0
复制
def change_case(s):
    return s[0].upper() + s[1:].lower()

s = "hello world"
result = change_case(s)
print(result)  # 输出 "Hello world"
  1. JavaScript
代码语言:javascript
复制
function changeCase(s) {
    return s[0].toUpperCase() + s.slice(1).toLowerCase();
}

let s = "hello world";
let result = changeCase(s);
console.log(result);  // 输出 "Hello world"
  1. Java
代码语言:java
复制
public class Main {
    public static String changeCase(String s) {
        return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
    }

    public static void main(String[] args) {
        String s = "hello world";
        String result = changeCase(s);
        System.out.println(result);  // 输出 "Hello world"
    }
}
  1. C#
代码语言:csharp
复制
using System;

class Program {
    static string ChangeCase(string s) {
        return char.ToUpper(s[0]) + s.Substring(1).ToLower();
    }

    static void Main() {
        string s = "hello world";
        string result = ChangeCase(s);
        Console.WriteLine(result);  // 输出 "Hello world"
    }
}
  1. PHP
代码语言:php
复制
function changeCase($s) {
    return ucfirst(strtolower($s));
}

$s = "hello world";
$result = changeCase($s);
echo $result;  // 输出 "Hello world"
  1. Ruby
代码语言:ruby
复制
def change_case(s)
    s[0].upcase + s[1..-1].downcase
end

s = "hello world"
result = change_case(s)
puts result  # 输出 "Hello world"
  1. Go
代码语言:go
复制
package main

import (
	"fmt"
	"strings"
)

func changeCase(s string) string {
	return strings.ToUpper(string(s[0])) + strings.ToLower(s[1:])
}

func main() {
	s := "hello world"
	result := changeCase(s)
	fmt.Println(result)  // 输出 "Hello world"
}

这些示例代码分别展示了如何在不同编程语言中实现更改字符串首字母的大小写。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券