자바를 사용하여 문자열의 첫 글자를 대문자화하려면 어떻게 해야 합니까?
문자열 예시
one thousand only
two hundred
twenty
seven
대문자로 된 문자열의 첫 번째 문자를 변경하고 다른 문자의 대소문자를 변경하지 않으려면 어떻게 해야 합니까?
변경 후에는 다음과 같이 해야 합니다.
One thousand only
Two hundred
Twenty
Seven
주의: apache.commons.lang은 사용하지 않습니다.이것을 하기 위한 명령.
라는 이름의 문자열의 첫 글자만 대문자화하려는 경우input
나머지는 그냥 놔둬요
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
지금이다output
네가 원하는 걸 가질 수 있을 거야체크해 주세요.input
사용 전 최소 1자 이상입니다.그렇지 않으면 예외가 발생합니다.
public String capitalizeFirstLetter(String original) {
if (original == null || original.length() == 0) {
return original;
}
return original.substring(0, 1).toUpperCase() + original.substring(1);
}
그냥... 완벽한 솔루션이죠. 결국 다른 모든 사람들이 =P에 올린 글들을 합친 셈이죠.
가장 간단한 방법은org.apache.commons.lang.StringUtils
학급
StringUtils.capitalize(Str);
또 있어요.org.springframework.util.StringUtils
Spring Framework:
StringUtils.capitalize(str);
apache commons-commons-commons-cap
String sentence = "ToDAY WeAthEr GREat";
public static String upperCaseWords(String sentence) {
String words[] = sentence.replaceAll("\\s+", " ").trim().split(" ");
String newSentence = "";
for (String word : words) {
for (int i = 0; i < word.length(); i++)
newSentence = newSentence + ((i == 0) ? word.substring(i, i + 1).toUpperCase():
(i != word.length() - 1) ? word.substring(i, i + 1).toLowerCase() : word.substring(i, i + 1).toLowerCase().toLowerCase() + " ");
}
return newSentence;
}
//Today Weather Great
여기 있습니다(이것이 아이디어를 얻기를 바랍니다).
/*************************************************************************
* Compilation: javac Capitalize.java
* Execution: java Capitalize < input.txt
*
* Read in a sequence of words from standard input and capitalize each
* one (make first letter uppercase; make rest lowercase).
*
* % java Capitalize
* now is the time for all good
* Now Is The Time For All Good
* to be or not to be that is the question
* To Be Or Not To Be That Is The Question
*
* Remark: replace sequence of whitespace with a single space.
*
*************************************************************************/
public class Capitalize {
public static String capitalize(String s) {
if (s.length() == 0) return s;
return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}
public static void main(String[] args) {
while (!StdIn.isEmpty()) {
String line = StdIn.readLine();
String[] words = line.split("\\s");
for (String s : words) {
StdOut.print(capitalize(s) + " ");
}
StdOut.println();
}
}
}
String s=t.getText().trim();
int l=s.length();
char c=Character.toUpperCase(s.charAt(0));
s=c+s.substring(1);
for(int i=1; i<l; i++)
{
if(s.charAt(i)==' ')
{
c=Character.toUpperCase(s.charAt(i+1));
s=s.substring(0, i) + c + s.substring(i+2);
}
}
t.setText(s);
간단한 라인 코드는 1개만 있으면 됩니다.한다면String A = scanner.nextLine();
첫 글자를 대문자로 한 문자열을 표시하려면 이 항목을 입력해야 합니다.
System.out.println(A.substring(0, 1).toUpperCase() + A.substring(1));
그리고 이제 끝이다.
첫 글자만 대문자로 쓰고 싶다면 아래 코드를 사용할 수 있습니다.
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
사실 피하면 최고의 퍼포먼스를 얻을 수 있어요.+
연산자 및 사용concat()
이 경우는,2개의 스트링만을 Marge 하는 경우에 최적인 옵션입니다(다만, 많은 스트링에는 그다지 적합하지 않습니다).이 경우 코드는 다음과 같습니다.
String output = input.substring(0, 1).toUpperCase().concat(input.substring(1));
StringTokenizer 클래스의 사용 예:
String st = " hello all students";
String st1;
char f;
String fs="";
StringTokenizer a= new StringTokenizer(st);
while(a.hasMoreTokens()){
st1=a.nextToken();
f=Character.toUpperCase(st1.charAt(0));
fs+=f+ st1.substring(1);
System.out.println(fs);
}
String Builder를 사용한 솔루션:
value = new StringBuilder()
.append(value.substring(0, 1).toUpperCase())
.append(value.substring(1))
.toString();
..이전 답변에 근거합니다.
모든 것을 합친다면, 끈의 앞부분에 여분의 여백을 위해 다듬는 것이 좋습니다.그렇지 않으면 .substring(0,1) to UpperCase는 공백 대문자화를 시도합니다.
public String capitalizeFirstLetter(String original) {
if (original == null || original.length() == 0) {
return original;
}
return original.trim().substring(0, 1).toUpperCase() + original.substring(1);
}
내 기능적 접근법전체 단락에서 흰색 경치 뒤에 첫 글자를 대문자로 표시합니다.
단어의 첫 글자만 대문자로 표기하려면 .split(" " " " )를 삭제하십시오.
b.name.split(" ")
.filter { !it.isEmpty() }
.map { it.substring(0, 1).toUpperCase()
+it.substring(1).toLowerCase() }
.joinToString(" ")
public static String capitalize(String str){
String[] inputWords = str.split(" ");
String outputWords = "";
for (String word : inputWords){
if (!word.isEmpty()){
outputWords = outputWords + " "+StringUtils.capitalize(word);
}
}
return outputWords;
}
2019년 7월 갱신
현재 이 작업을 수행하기 위한 최신 라이브러리 기능은 다음과 같습니다.org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.StringUtils;
StringUtils.capitalize(myString);
Maven을 사용하는 경우 pom.xml에 의존관계를 Import합니다.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
"간단한" 코드라도, 저는 도서관을 이용합니다.문제는 코드 자체가 아니라 예외적인 경우를 다루는 기존의 테스트 케이스입니다.이 경우null
, 빈 문자열, 기타 언어 문자열.
단어 조작 부분은 Apache Commons Lang에서 이동되었습니다.이제 Apache Commons Text에 배치되었습니다.https://search.maven.org/artifact/org.apache.commons/commons-text 에서 입수할 수 있습니다.
Apache Commons Text에서 WordUtils.capitalize(String str)를 사용할 수 있습니다.그것은 당신이 요구한 것보다 더 강력합니다.또한 풀(full)을 대문자로 사용할 수 있습니다(예: 고정)."oNe tousand only"
를 참조해 주세요.
완전한 텍스트에서 작동하기 때문에 첫 번째 단어만 대문자로 표시하도록 지시해야 합니다.
WordUtils.capitalize("one thousand only", new char[0]);
Full JUnit 클래스를 사용하여 다음 기능을 사용할 수 있습니다.
package io.github.koppor;
import org.apache.commons.text.WordUtils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class AppTest {
@Test
void test() {
assertEquals("One thousand only", WordUtils.capitalize("one thousand only", new char[0]));
}
}
사용방법:
char[] chars = {Character.toUpperCase(A.charAt(0)),
Character.toUpperCase(B.charAt(0))};
String a1 = chars[0] + A.substring(1);
String b1 = chars[1] + B.substring(1);
「 」가 되어 있는 input
★★★★★★★★★★★★★★★★★★:
Character.toUpperCase(input.charAt(0)) + input.substring(1).toLowerCase()
다음 코드를 사용해 볼 수 있습니다.
public string capitalize(str) {
String[] array = str.split(" ");
String newStr;
for(int i = 0; i < array.length; i++) {
newStr += array[i].substring(0,1).toUpperCase() + array[i].substring(1) + " ";
}
return newStr.trim();
}
수락된 답변에 NULL 체크와 IndexOutOfBoundsException을 추가하고 싶습니다.
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
자바 코드:
class Main {
public static void main(String[] args) {
System.out.println("Capitalize first letter ");
System.out.println("Normal check #1 : ["+ captializeFirstLetter("one thousand only")+"]");
System.out.println("Normal check #2 : ["+ captializeFirstLetter("two hundred")+"]");
System.out.println("Normal check #3 : ["+ captializeFirstLetter("twenty")+"]");
System.out.println("Normal check #4 : ["+ captializeFirstLetter("seven")+"]");
System.out.println("Single letter check : ["+captializeFirstLetter("a")+"]");
System.out.println("IndexOutOfBound check : ["+ captializeFirstLetter("")+"]");
System.out.println("Null Check : ["+ captializeFirstLetter(null)+"]");
}
static String captializeFirstLetter(String input){
if(input!=null && input.length() >0){
input = input.substring(0, 1).toUpperCase() + input.substring(1);
}
return input;
}
}
출력:
Normal check #1 : [One thousand only]
Normal check #2 : [Two hundred]
Normal check #3 : [Twenty]
Normal check #4 : [Seven]
Single letter check : [A]
IndexOutOfBound check : []
Null Check : [null]
다음은 inputString 값에 관계없이 동일한 출력을 제공합니다.
if(StringUtils.isNotBlank(inputString)) {
inputString = StringUtils.capitalize(inputString.toLowerCase());
}
String의 1.을합니다. String string stringsubstring()
★★★
public static String capitalize(String str) {
if(str== null || str.isEmpty()) {
return str;
}
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
그냥 capitalize()
문자열의 첫 글자를 대문자로 변환하는 방법:
System.out.println(capitalize("stackoverflow")); // Stackoverflow
System.out.println(capitalize("heLLo")); // HeLLo
System.out.println(capitalize(null)); // null
2. Apache Commons Lang
StringUtils
는 Commons Lang을 합니다.capitalize()
할 수 :
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
(Maven 용용):
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
여기 이 두 가지 접근법에 대해 자세히 설명하는 기사가 있습니다.
class Test {
public static void main(String[] args) {
String newString="";
String test="Hii lets cheCk for BEING String";
String[] splitString = test.split(" ");
for(int i=0; i<splitString.length; i++){
newString= newString+ splitString[i].substring(0,1).toUpperCase()
+ splitString[i].substring(1,splitString[i].length()).toLowerCase()+" ";
}
System.out.println("the new String is "+newString);
}
}
언급URL : https://stackoverflow.com/questions/5725892/how-to-capitalize-the-first-letter-of-word-in-a-string-using-java
'programing' 카테고리의 다른 글
Java InputStream의 콘텐츠를 OutputStream에 쉽게 쓰는 방법 (0) | 2022.07.21 |
---|---|
Java에서 "instance of" 사용 (0) | 2022.07.21 |
Vue 2에서 비반응 구성 요소 데이터를 설정하는 방법 (0) | 2022.07.21 |
Vuex에서 AssertionError를 {개체(유형, 텍스트)}과(와) 동일하게 던지는 단위 테스트 (0) | 2022.07.21 |
C의 거듭제곱으로? (0) | 2022.07.21 |