大写的第一个字符 [英] First char to upper case

查看:167
本文介绍了大写的第一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何在字符串中每个第一个字母大写?


使字符串小写的第一个字符最有效的方法?

我想将字符串的第一个字母转换为大写字母。我正在尝试使用JavaDocs中描述的replaceFirst(),但我不知道正则表达式的含义。

I want to convert the first letter of a string to upper case. I am attempting to use replaceFirst() as described in JavaDocs, but I have no idea what is meant by regular expression.

这是我到目前为止尝试的代码:

Here is the code I have tried so far:

public static String cap1stChar(String userIdea)
{
    String betterIdea, userIdeaUC;
    char char1;
    userIdeaUC = userIdea.toUpperCase();
    char1 = userIdeaUC.charAt(0);
    betterIdea = userIdea.replaceFirst(char1); 
    return betterIdea;
}//end cap1stChar

编译器错误是参数列表的长度不同。我认为这是因为缺少正则表达式,但我不知道究竟是什么。

The compiler error is that the argument lists differ in lengths. I presume that is because the regex is missing, however I don't know what that is exactly.

推荐答案

正则表达式(缩写为regex或reg-ex)是一个定义搜索模式的字符串。

Regular Expressions (abbreviated "regex" or "reg-ex") is a string that defines a search pattern.

什么是 replaceFirst()它是否使用参数中提供的正则表达式并用搜索结果替换搜索中的第一个结果你传入另一​​个参数。

What replaceFirst() does is it uses the regular expression provided in the parameters and replaces the first result from the search with whatever you pass in as the other parameter.

你想要做的是使用 String class' charAt() 方法,然后使用 Character.toUpperCase()将字符更改为大写(显然) 。您的代码如下所示:

What you want to do is convert the string to an array using the String class' charAt() method, and then use Character.toUpperCase() to change the character to upper case (obviously). Your code would look like this:

char first = Character.toUpperCase(userIdea.charAt(0));
betterIdea = first + userIdea.substring(1);

或者,如果您对更复杂,单行的Java代码感到满意:

Or, if you feel comfortable with more complex, one-lined java code:

betterIdea = Character.toUpperCase(userIdea.charAt(0)) + userIdea.substring(1);

这两个都做同样的事情,即转换的第一个字符userIdea 为大写字符。

Both of these do the same thing, which is converting the first character of userIdea to an upper case character.

这篇关于大写的第一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆