Java에서 문자열의 첫 글자를 대문자로 표시하는 방법은 무엇입니까?
하여 ★★★★★★★★★★★★★★★★★★★★★★★★★★★」String
사자사이 입력의 첫 글자를 대문자로 쓰려고 합니다.
이거 해봤어요.
String name;
BufferedReader br = new InputStreamReader(System.in);
String s1 = name.charAt(0).toUppercase());
System.out.println(s1 + name.substring(1));
그 결과, 다음의 컴파일러 에러가 발생했습니다.
-
유형 불일치: InputStreamReader에서 BufferedReader로 변환할 수 없습니다.
-
기본 형식 char에서 Uppercase()를 호출할 수 없습니다.
String str = "java";
String cap = str.substring(0, 1).toUpperCase() + str.substring(1);
// cap = "Java"
예를 들어 다음과 같습니다.
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Actually use the Reader
String name = br.readLine();
// Don't mistake String object with a Character object
String s1 = name.substring(0, 1).toUpperCase();
String nameCapitalized = s1 + name.substring(1);
System.out.println(nameCapitalized);
}
StringUtils.capitalize(..)
일반인으로부터
String 의 첫 글자를 대문자로 하는 보다 짧은/빠른 버전 코드는 다음과 같습니다.
String name = "stackoverflow";
name = name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase();
의 의 값name
"Stackoverflow"
Apache의 공용 라이브러리를 사용합니다.이러한 문제로부터 뇌를 해방하고, 특수한 포인터와 인덱스를 제외하는 예외를 회피합니다.
순서 1:
의 공통 언어 .build.gradle
관계
compile 'org.apache.commons:commons-lang3:3.6'
순서 2:
문자열이 모두 소문자이거나 첫 글자를 초기화하기만 하면 됩니다.직접 문의해 주세요.
StringUtils.capitalize(yourString);
요.enum
콜, 콜, 콜toLowerCase()
먼저, 그리고 그것이 던져진다는 것을 명심하세요.NullPointerException
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
StringUtils.capitalize(YourEnum.STUFF.name().toLowerCase());
StringUtils.capitalize(yourString.toLowerCase());
다음은 Apache에서 제공하는 샘플입니다.예외 없이 무료입니다
StringUtils.capitalize(null) = null
StringUtils.capitalize("") = ""
StringUtils.capitalize("cat") = "Cat"
StringUtils.capitalize("cAt") = "CAt"
StringUtils.capitalize("'cat'") = "'cat'"
주의:
WordUtils
는 이 라이브러리에도 포함되어 있지만 권장되지 않습니다.당신은 그것을 사용하지 마세요.
자바:
모든 문자열을 대문자로 표시하는 단순한 도우미 방법입니다.
public static String capitalize(String str)
{
if(str == null) return str;
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
에 그냥 하면 돼요.str = capitalize(str)
코틀린:
str.capitalize()
스프링을 사용하는 경우:
import static org.springframework.util.StringUtils.capitalize;
...
return capitalize(name);
구현: org/springframework/util/StringUtils.java)L535-L555
REF: javadoc-api/org/springframework/util/StringUtils.html#대문자로 쓰다
메모:만약 당신이 이미 아파치 공통 랭 의존한 다음 다른 대답은 추천한다 그들의 StringUtils.capitalize.
고작 하고 싶은 아마도 이 있다.
s1 = name.substring(0, 1).toUpperCase() + name.substring(1);
(대문자로 변환되고 원본 문자열의 나머지를 더해 첫번째 char로 변환합니다).
또한지만 어떤 라인을 읽지 않는 입력 스트림 판독기를 만들어 낸다. ★★★★★★★★★★★★★★★★★▼name
★★★★null
.
이 일해야 한다:
BufferedReader br = new InputstreamReader(System.in);
String name = br.readLine();
String s1 = name.substring(0, 1).toUpperCase() + name.substring(1);
WordUtils.capitalize(java.lang.)아파치 공용에서 String.
해결책 아래는 일할 것이다.
String A = "stackOverflow";
String ACaps = A.toUpperCase().charAt(0)+A.substring(1,A.length());
//Will print StackOverflow
당신은 원시적인 잡일에 오지만 혹시 Uppercase에 먼저, 위에서 표시한 부분 문자열에 추가할 첫번째 차를 전체 String을 만들 수 있toUpperCase()사용할 수 없습니다.
사용 WordUtils.capitalize(공백이).
수도에서 다 먼저 편지를 받고 이 유틸리티 메서드를 사용합니다.
String captializeAllFirstLetter(String name)
{
char[] array = name.toCharArray();
array[0] = Character.toUpperCase(array[0]);
for (int i = 1; i < array.length; i++) {
if (Character.isWhitespace(array[i - 1])) {
array[i] = Character.toUpperCase(array[i]);
}
}
return new String(array);
}
문자열을 소문자로 설정하고 첫 번째 문자를 다음과 같이 대문자로 설정합니다.
userName = userName.toLowerCase();
첫 글자를 대문자로 표시합니다.
userName = userName.substring(0, 1).toUpperCase() + userName.substring(1).toLowerCase();
서브스트링은 더 큰 끈의 한 조각을 얻는 것 뿐이고, 우리는 그것들을 다시 결합하는 것입니다.
String str1 = "hello";
str1.substring(0, 1).toUpperCase()+str1.substring(1);
IT는 101% 동작합니다.
public class UpperCase {
public static void main(String [] args) {
String name;
System.out.print("INPUT: ");
Scanner scan = new Scanner(System.in);
name = scan.next();
String upperCase = name.substring(0, 1).toUpperCase() + name.substring(1);
System.out.println("OUTPUT: " + upperCase);
}
}
최단 거리도:
String message = "my message";
message = Character.toUpperCase(message.charAt(0)) + message.substring(1);
System.out.println(message) // Will output: My message
나한테는 통했어
Android에서 문자열의 첫 글자를 대문자로 표시 가능한 모든 옵션에 대한 자세한 토픽에 대한 내 기사입니다.
Java에서 문자열의 첫 글자를 대문자로 변환하는 방법
public static String capitalizeString(String str) {
String retStr = str;
try { // We can face index out of bound exception if the string is null
retStr = str.substring(0, 1).toUpperCase() + str.substring(1);
}catch (Exception e){}
return retStr;
}
KOTLIN에서 문자열의 첫 글자를 대문자로 표시하는 방법
fun capitalizeString(str: String): String {
var retStr = str
try { // We can face index out of bound exception if the string is null
retStr = str.substring(0, 1).toUpperCase() + str.substring(1)
} catch (e: Exception) {
}
return retStr
}
Android Studio에서
를 더하면 됩니다.build.gradle (Module: app)
dependencies {
...
compile 'org.apache.commons:commons-lang3:3.1'
...
}
이제 사용할 수 있습니다.
String string = "STRING WITH ALL CAPPS AND SPACES";
string = string.toLowerCase(); // Make all lowercase if you have caps
someTextView.setText(WordUtils.capitalize(string));
Word Utils. 대문자로 표시해 주세요.완전()?
import org.apache.commons.lang3.text.WordUtils;
public class Main {
public static void main(String[] args) {
final String str1 = "HELLO WORLD";
System.out.println(capitalizeFirstLetter(str1)); // output: Hello World
final String str2 = "Hello WORLD";
System.out.println(capitalizeFirstLetter(str2)); // output: Hello World
final String str3 = "hello world";
System.out.println(capitalizeFirstLetter(str3)); // output: Hello World
final String str4 = "heLLo wORld";
System.out.println(capitalizeFirstLetter(str4)); // output: Hello World
}
private static String capitalizeFirstLetter(String str) {
return WordUtils.capitalizeFully(str);
}
}
다음의 조작도 실행할 수 있습니다.
String s1 = br.readLine();
char[] chars = s1.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
s1= new String(chars);
System.out.println(s1);
서브스트링을 사용하는 것보다 더 좋다(최적화). (단, 작은 스트링에 대해서는 걱정할 필요가 없습니다.)
하시면 됩니다.substring()
이 일을 하기 위해서.
하지만 두 가지 다른 경우가 있습니다.
케이스 1
경우,String
대문자로 하는 것은 사람이 사용하는 것을 의미합니다.기본 로케일도 지정해야 합니다.
String firstLetterCapitalized =
myString.substring(0, 1).toUpperCase(Locale.getDefault()) + myString.substring(1);
케이스 2
경우,String
로 쓰는 .용하사Locale.getDefault()
, 이 같은 로케일을 하기 때문입니다를 들어, " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " "toUpperCase(Locale.ENGLISH)
이렇게 하면 내부 처리에 사용하는 문자열이 일관되게 유지되므로 찾기 어려운 버그를 방지할 수 있습니다.
의: 다음음음음음음 note note note note note note note note note note note note note 를 지정할 필요는 없습니다.Locale.getDefault()
★★★★★★에toLowerCase()
이치노
이거 드셔보세요.
이 방법은 "hello world"라는 단어를 생각해 보세요.이 방법은 각 단어의 선두를 대문자로 하여 "hello world"로 바꿉니다.
private String capitalizer(String word){
String[] words = word.split(" ");
StringBuilder sb = new StringBuilder();
if (words[0].length() > 0) {
sb.append(Character.toUpperCase(words[0].charAt(0)) + words[0].subSequence(1, words[0].length()).toString().toLowerCase());
for (int i = 1; i < words.length; i++) {
sb.append(" ");
sb.append(Character.toUpperCase(words[i].charAt(0)) + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
}
}
return sb.toString();
}
현재 답변이 잘못되었거나 이 간단한 작업이 지나치게 복잡합니다.몇 가지 조사를 실시한 후, 다음의 2개의 어프로치를 생각해 냈습니다.
의 1. 스트링의substring()
★★★
public static String capitalize(String str) {
if(str== null || str.isEmpty()) {
return str;
}
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
예:
System.out.println(capitalize("java")); // Java
System.out.println(capitalize("beTa")); // BeTa
System.out.println(capitalize(null)); // null
2. Apache Commons Lang
는 Apache Commons Lang을 제공합니다.StringUtils
위한 : "이러한 클래스":
System.out.println(StringUtils.capitalize("apache commons")); // Apache commons
System.out.println(StringUtils.capitalize("heLLO")); // HeLLO
System.out.println(StringUtils.uncapitalize(null)); // null
도 꼭 해 주세요.pom.xml
삭제:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
심플한 솔루션!은 외부 라이브러리가 필요 없습니다.빈 문자열이나 1글자 문자열을 처리할 수 있습니다.
private String capitalizeFirstLetter(@NonNull String str){
return str.length() == 0 ? str
: str.length() == 1 ? str.toUpperCase()
: str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
}
첫 글자의 대문자와 기타 작은 글자를 얻으려면 아래 코드를 사용하십시오.서브스트링 기능을 완료했습니다.
String currentGender="mAlE";
currentGender=currentGender.substring(0,1).toUpperCase()+currentGender.substring(1).toLowerCase();
여기서 서브스트링(0,1)에서 UpperCase()로 변환하고 서브스트링(1)에서 나머지 모든 문자를 작은 대소문자로 변환합니다.
출력:
남자
네가 그렇게 틀리지 않았다는 걸 보여주기 위해서야
BufferedReader br = new InputstreamReader(System.in);
// Assuming name is not blank
String name = br.readLine();
//No more error telling that you cant convert char to string
String s1 = (""+name.charAt(0)).toUppercase());
// Or, as Carlos prefers. See the comments to this post.
String s1 = Character.toString(name.charAt(0)).toUppercase());
System.out.println(s1+name.substring(1));
주의: 이것은 그것을 하기에 전혀 좋은 방법이 아니다.이것은 단지 OP에 다음을 사용하여 수행할 수 있음을 보여주기 위한 것입니다.charAt()
뿐만 아니라.;)
이거면 될 거야
char[] array = value.toCharArray();
array[0] = Character.toUpperCase(array[0]);
String result = new String(array);
다음의 코드를 사용할 수 있습니다.
public static void main(String[] args) {
capitalizeFirstLetter("java");
capitalizeFirstLetter("java developer");
}
public static void capitalizeFirstLetter(String text) {
StringBuilder str = new StringBuilder();
String[] tokens = text.split("\\s");// Can be space,comma or hyphen
for (String token : tokens) {
str.append(Character.toUpperCase(token.charAt(0))).append(token.substring(1)).append(" ");
}
str.toString().trim(); // Trim trailing space
System.out.println(str);
}
주어진 답변은 한 단어의 첫 글자를 대문자로만 표시하기 위한 것입니다.다음 코드를 사용하여 전체 문자열을 대문자로 지정합니다.
public static void main(String[] args) {
String str = "this is a random string";
StringBuilder capitalizedString = new StringBuilder();
String[] splited = str.trim().split("\\s+");
for (String string : splited) {
String s1 = string.substring(0, 1).toUpperCase();
String nameCapitalized = s1 + string.substring(1);
capitalizedString.append(nameCapitalized);
capitalizedString.append(" ");
}
System.out.println(capitalizedString.toString().trim());
}
출력:This Is A Random String
[ Input ](입력)이 [UpperCase](상대문자)인 경우 다음을 사용합니다.
str.substring(0, 1)을 UpperCase() + str로 지정합니다.서브스트링(1)~LowerCase();
[ Input ](입력)이 [LowerCase](소문자)인 경우 다음을 사용합니다.
str.substring(0, 1)을 UpperCase() + str로 지정합니다.서브스트링(1);
사용.commons.lang.StringUtils
가장 좋은 답은 다음과 같습니다.
public static String capitalize(String str) {
int strLen;
return str != null && (strLen = str.length()) != 0 ? (new StringBuffer(strLen)).append(Character.toTitleCase(str.charAt(0))).append(str.substring(1)).toString() : str;
}
String Buffer로 끈을 감아서 멋져요.String Buffer는 같은 인스턴스를 사용하여 원하는 대로 조작할 수 있습니다.
언급URL : https://stackoverflow.com/questions/3904579/how-to-capitalize-the-first-letter-of-a-string-in-java
'programing' 카테고리의 다른 글
vuex: 상태 필드 "foo"가 "foo"에서 이름이 같은 모듈에 의해 재정의되었습니다. (0) | 2022.08.16 |
---|---|
vue 컴포넌트와 앱에서 el과 template의 차이점은 무엇입니까? (0) | 2022.08.16 |
C/C++ 글로벌과 스태틱 글로벌 (0) | 2022.08.16 |
진입점 - webpack.config.js vs vue.config.js (0) | 2022.08.16 |
'더블' 대 '더블' 정밀도 (0) | 2022.08.16 |