문자열 예
one thousand only
two hundred
twenty
seven
대문자로 문자열의 첫 문자를 변경하고 다른 문자의 대소 문자를 변경하지 않으려면 어떻게합니까?
변경 후 다음과 같아야합니다.
One thousand only
Two hundred
Twenty
Seven
참고 :이 작업을 수행하기 위해 apache.commons.lang.WordUtils를 사용하고 싶지 않습니다.
문자열 예
one thousand only
two hundred
twenty
seven
대문자로 문자열의 첫 문자를 변경하고 다른 문자의 대소 문자를 변경하지 않으려면 어떻게합니까?
변경 후 다음과 같아야합니다.
One thousand only
Two hundred
Twenty
Seven
참고 :이 작업을 수행하기 위해 apache.commons.lang.WordUtils를 사용하고 싶지 않습니다.
답변:
이름이 지정된 문자열의 첫 글자 만 대문자로 input하고 나머지는 그대로 두려면 다음을 수행하십시오.
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
이제 output당신이 원하는 것을 가질 것입니다. input이것을 사용하기 전에 적어도 한 자 이상인지 확인하십시오 . 그렇지 않으면 예외가 발생합니다.
public String capitalizeFirstLetter(String original) {
if (original == null || original.length() == 0) {
return original;
}
return original.substring(0, 1).toUpperCase() + original.substring(1);
}
그냥 ... 완벽한 해결책, 다른 사람들이 결국 = P를 게시 한 것을 결합한 것 같습니다.
return original.length() == 0 ? original : original.substring(0, 1).toUpperCase() + original.substring(1);
if length() == 0, 우리는 그것이 ""아니라고 대신 말할 수는 없지만 original? 하나의 라이너에 몇 문자를 저장합니다. Java가 너무 많은 언어로 느껴지기 때문에 나는 길이가 0 인 문자열을 갖는 다른 방법이 있다면 솔직히 놀라지 않을 것입니다.
String.toUpperCase(Locale)로케일이 텍스트와 일치해야하므로 임의의 문자열 에 사용할 수 없습니다 . 네, 사용되어야하지만 항상하는 분명하지 않다 Locale사용하는 ...
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
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);
여기 있습니다 (이것이 당신에게 아이디어를 주길 바랍니다) :
/*************************************************************************
* 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();
}
}
}
StdIn과 StdOut매우 자바 Y 없습니다. :-)
이 작업에는 한 줄의 코드 만 있으면됩니다. 그렇다면 String A = scanner.nextLine();
대문자로 된 첫 글자로 문자열을 표시하려면 이것을 작성해야합니다.
System.out.println(A.substring(0, 1).toUpperCase() + A.substring(1));
그리고 이제 끝났습니다.
모든 것을 함께 추가하면 문자열의 시작 부분에 공백을 추가로 자르는 것이 좋습니다. 그렇지 않으면 .substring (0,1) .toUpperCase는 공백을 대문자로 시도합니다.
public String capitalizeFirstLetter(String original) {
if (original == null || original.length() == 0) {
return original;
}
return original.trim().substring(0, 1).toUpperCase() + original.substring(1);
}
2019 년 7 월 업데이트
현재이 작업을 수행하는 가장 최신 라이브러리 기능은
org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.StringUtils;
StringUtils.capitalize(myString);
Maven을 사용하는 경우 pom.xml에서 종속성을 가져 오십시오.
<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) 를 사용할 수 있습니다 . 요청한 것보다 더 강력합니다. 또한 전체를 대문자로 표시 할 수도 있습니다 (예 : 고정 "oNe tousand only").
완전한 텍스트에서 작동하기 때문에 첫 단어 만 대문자로 표기해야합니다.
WordUtils.capitalize("one thousand only", new char[0]);
기능을 사용할 수있는 전체 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]));
}
}
첫 글자 만 대문자로 바꾸려면 아래 코드를 사용할 수 있습니다
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
이것을 사용하십시오 :
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 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;
}
허용 된 답변에 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());
}
substring()방법 사용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
StringUtilsCommons 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);
}
}