Java-在字符串中切换字母大小写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31227232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java-toggle alphabet case in string
提问by ecain
I have my code to switch the case from upper to lower and vice versa. I also have it to where it will toggle upper to lower, and lower to upper. My question is; is there a way I can get it to also include the character such as a comma or a period. For example, if I type in the string "Hello, there." I will get: "HELLO, THERE.", "hello, there" and "hELLOTHERE". How can I get it to where my third output will say "hELLO, THERE."
我有我的代码可以将案例从上切换到下,反之亦然。我也有它可以从上到下,从下到上切换的地方。我的问题是;有没有办法让它也包含诸如逗号或句点之类的字符。例如,如果我输入字符串“Hello, there”。我会得到:“你好,那里。”、“你好,那里”和“你好”。我怎样才能让它到达我的第三个输出会说“你好,那里”的地方。
import java.util.*;
public class UpperLower2
{
public static void main(String[] args)
{
System.out.println("Enter in a sentence:");
Scanner input = new Scanner(System.in);
String sentence = input.nextLine();
System.out.println("All uppercase:" + sentence.toUpperCase());
System.out.println("All lowercase:" + sentence.toLowerCase());
System.out.println("Converted String:" + toggleString(sentence));
input.close();
}
public static String toggleString(String sentence)
{
String toggled = "";
for(int i=0; i<sentence.length(); i++)
{
char letter = sentence.charAt(i);
if(Character.isUpperCase(sentence.charAt(i)))
{
letter = Character.toLowerCase(letter);
toggled = toggled + letter;
}
else if(Character.isLowerCase(sentence.charAt(i)))
{
letter = Character.toUpperCase(letter);
toggled = toggled + letter;
}
}
return toggled;
}
}
}
回答by Mureinik
If a character is neither upper case nor lowercase, you should just take it as is. Also, don't use a String
to accumulate your output - this is what StringBuilder
s are for:
如果一个字符既不是大写也不是小写,你应该照原样接受它。另外,不要使用 aString
来累积您的输出 - 这就是StringBuilder
s 的用途:
public static String toggleString(String sentence) {
StringBuilder toggled = new StringBuilder(sentence.length());
for (char letter : sentence.toCharArray()) {
if(Character.isUpperCase(letter)) {
letter = Character.toLowerCase(letter);
} else if(Character.isLowerCase(letter)) {
letter = Character.toUpperCase(letter);
}
toggled.append(letter);
}
return toggled.toString();
}
EDIT:
A similar implementation in Java 8 semantics, without having to loop over the string yourself:
编辑:
Java 8 语义中的类似实现,而不必自己遍历字符串:
public static String toggleStringJava8(String sentence) {
return sentence.chars().mapToObj(c -> {
if (Character.isUpperCase(c)) {
c = Character.toLowerCase(c);
} else if (Character.isLowerCase(c)) {
c = Character.toUpperCase(c);
}
return String.valueOf((char)c);
}).collect(Collectors.joining());
}
回答by 027
Use the Apache commons lang API StringUtils class. UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize - changes the case of a String
使用 Apache commons lang API StringUtils 类。UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize - 改变字符串的大小写
To toggle the cases, Use the
要切换案例,请使用
swapCase(String str)
Swaps the case of a String changing upper and title case to lower case, and lower case to upper case.
交换案例(字符串 str)
交换字符串的大小写,将大写和标题大小写更改为小写,将小写更改为大写。
Also you do not need to write any code to handle ' or . or any other these kind of characters.String Util will do it all..
此外,您无需编写任何代码来处理 ' 或 . 或任何其他此类字符。String Util 将完成所有工作..
Example:
例子:
String inputString = "Hello, there";
System.out.println(StringUtils.swapCase(inputString));
System.out.println(StringUtils.upperCase(inputString));
System.out.println(StringUtils.lowerCase(inputString));
Output:
hELLO, THERE
HELLO, THERE
hello, there
输出:
您好,有
您好,有
你好,有
回答by Erwin Bolwidt
Given the source code that you posted, you now have an if-statement with two branches: one for the case where the character was upper-case and one when the character was lower-case. Characters like comma and other punctuation symbols don't have upper or lower-case, so they are ignored by your if-statement and else-block.
根据您发布的源代码,您现在有一个带有两个分支的 if 语句:一个用于字符为大写的情况,另一个用于字符为小写的情况。逗号和其他标点符号等字符没有大写或小写,因此您的 if 语句和 else 块会忽略它们。
To work around that, add another else
block to the statement:
要解决这个问题,请else
在语句中添加另一个块:
else {
toggled = toggled + letter;
}
After you have that working, you should look into making your code cleaner.
完成这项工作后,您应该考虑使代码更简洁。
You now have the statement toggled = toggled + letter;
three times in your code; you can change that into one time:
现在toggled = toggled + letter;
,您的代码中有3 次语句;您可以将其更改为一次:
char letter = sentence.charAt(i);
if(Character.isUpperCase(sentence.charAt(i)))
{
letter = Character.toLowerCase(letter);
}
else if(Character.isLowerCase(sentence.charAt(i)))
{
letter = Character.toUpperCase(letter);
}
// else {
// }
// You can remove the latest `else` branch now, because it is empty.
toggled = toggled + letter;
Also, the preferred way to build strings in Java is using StringBuilder
instead of the +
operator on strings. If you search on StackOverflow for StringBuilder
you'll get plenty of examples on how to use that.
此外,在 Java 中构建字符串的首选方法是在字符串上使用StringBuilder
而不是+
运算符。如果你在 StackOverflow 上搜索StringBuilder
你会得到很多关于如何使用它的例子。
回答by Ronit Oommen
We can simply convert the incoming String into char[] and then toggle them individually. Worked for me!!!
我们可以简单地将传入的 String 转换为 char[],然后单独切换它们。对我来说有效!!!
import java.util.Scanner;
@SuppressWarnings("unused")
public class One {
public static void main(String[] args) {
System.out.println("Enter a Word with toggled alphabets");
Scanner sc=new Scanner(System.in);
String line =sc.nextLine();
char[] arr= line.toCharArray();
for(char ch: arr)
{
if(Character.isUpperCase(ch)){
ch= Character.toLowerCase(ch);
}
else if(Character.isLowerCase(ch)){
ch= Character.toUpperCase(ch);
}
System.out.print(ch);
}}}
回答by VHS
You can do it with one line of code in Java 8:
您可以使用 Java 8 中的一行代码来完成:
String newText = text.chars()
.mapToObj(ch -> Character.isLowerCase(ch) ? String.valueOf(Character.toUpperCase((char)ch)) : String.valueOf(Character.toLowerCase((char)ch)))
.collect(Collectors.joining());
String newText = text.chars()
.mapToObj(ch -> Character.isLowerCase(ch) ? String.valueOf(Character.toUpperCase((char)ch)) : String.valueOf(Character.toLowerCase((char)ch)))
.collect(Collectors.joining());
回答by Binny Chelziah M
We can do this by comparing all the characters of the string with all the upper case and lowercase alphabets. If the character matches with uppercase alphabet, replace it with corresponding lowercase and vice versa.
我们可以通过将字符串的所有字符与所有大写和小写字母进行比较来做到这一点。如果字符与大写字母匹配,则将其替换为相应的小写字母,反之亦然。
import java.util.Scanner;
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner scan = new Scanner(System.in);
String S = scan.next();
char []a ={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
char []b ={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
char [] ch = S.toCharArray();
for(int i=0;i<ch.length;i++){
for(int j=0;j<a.length;j++){
if(ch[i]==a[j]){
ch[i]=b[j];
}
else if(ch[i]==b[j]){
ch[i]=a[j];
}
}
}
String text = new String(ch);
System.out.println(text);
}
}
回答by Vineethkumar Marpadge
Using bit manipulation:
使用位操作:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
String s= scan.next();
for(int i=0;i<s.length();i++){
System.out.print((char)(s.charAt(i)^32));
}
}
}