Java를 사용하여 문자열의 첫 글자를 대문자로 바꾸는 방법은 무엇입니까?
문자열 예
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를 게시 한 것을 결합하는 것을 보았습니다.
가장 간단한 방법은 org.apache.commons.lang.StringUtils
클래스 를 사용하는 것 입니다
StringUtils.capitalize(Str);
또한,이 org.springframework.util.StringUtils
에 스프링 프레임 워크 :
StringUtils.capitalize(str);
에서 아파치 평민 - 랭 .
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();
}
}
}
이 작업에는 한 줄의 코드 만 있으면됩니다. 그렇다면 String A = scanner.nextLine();
대문자로 된 첫 글자로 문자열을 표시하려면 이것을 작성해야합니다.
System.out.println(A.substring(0, 1).toUpperCase() + A.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);
}
모든 것을 함께 추가하면 문자열의 시작 부분에 공백을 추가로 자르는 것이 좋습니다. 그렇지 않으면 .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>
StringBuilder를 사용한 솔루션 :
value = new StringBuilder()
.append(value.substring(0, 1).toUpperCase())
.append(value.substring(1))
.toString();
.. 이전 답변을 바탕으로
이것을 사용하십시오 :
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();
}
My functional approach. its capstilise first character in sentence after whitescape in whole paragraph.
For capatilising only first character of the word just remove .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;
}
I would like to add a NULL check and IndexOutOfBoundsException on the accepted answer.
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
Java Code:
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;
}
}
Output:
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]
The following will give you the same consistent output regardless of the value of your inputString:
if(StringUtils.isNotBlank(inputString)) {
inputString = StringUtils.capitalize(inputString.toLowerCase());
}
1. Using String's substring()
Method
public static String capitalize(String str) {
if(str== null || str.isEmpty()) {
return str;
}
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
Now just call the capitalize()
method to convert the first letter of a string to uppercase:
System.out.println(capitalize("stackoverflow")); // Stackoverflow
System.out.println(capitalize("heLLo")); // HeLLo
System.out.println(capitalize(null)); // null
2. Apache Commons Lang
The StringUtils
class from Commons Lang provides the capitalize()
method that can also be used for this purpose:
System.out.println(StringUtils.capitalize("apache commons")); // Apache commons
System.out.println(StringUtils.capitalize("heLLO")); // HeLLO
System.out.println(StringUtils.uncapitalize(null)); // null
Add the following dependency to your pom.xml
file (for Maven only):
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
Here is an article that explains these two approaches in detail.
Simplest way to do is:
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);
}
}
'Programing' 카테고리의 다른 글
NodeJS를 사용하여 UTC 날짜를 YYYY-MM-DD hh : mm : ss 문자열로 포맷하는 방법은 무엇입니까? (0) | 2020.05.01 |
---|---|
@property는 Objective-C에서 비 원자 유지, 할당, 복사, (0) | 2020.05.01 |
Linux 명령 행을 사용하여 Node.JS를 설치 제거 하시겠습니까? (0) | 2020.05.01 |
누군가 SQL 쿼리를 저작권으로 보호 할 수 있습니까? (0) | 2020.05.01 |
보다 큼 /보다 큼에 대한 스위치 설명 (0) | 2020.05.01 |