[英]How do I replace more than one type of Character in Java String
newbie here.新手在这里。 Any help with this problem would be appreciated:
任何有关此问题的帮助将不胜感激:
You are given a String variable called data that contain letters and spaces only.
您将获得一个名为data的字符串变量,该变量仅包含字母和空格。 Write the Java class to print a modified version of the String where all lowercase letters are replaced by
?
编写 Java 类以打印字符串的修改版本,其中所有小写字母都被替换为
?
and all whitespaces are replaced by+
.并且所有空格都替换为
+
。 An example is shown below:I Like Java
becomesI+L???+J???
一个例子如下所示:
I Like Java
变成了I+L???+J???
..
What I have so far:到目前为止我所拥有的:
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String data;
//prompt
System.out.println("Enter a sentence: ");
//input
data = input.nextLine();
for (int i = 0; i < data.length(); i++) {
if (Character.isWhitespace(data.charAt(i))) {
data.replace("", "+");
if (Character.isLowerCase(data.charAt(i))) {
data.replace(i, i++, ); //not sure what to include here
}
} else {
System.out.print(data);
}
}
}
any suggestions would be appreciated.任何建议,将不胜感激。
Firstly, you are trying to make changes to String object which is immutable.首先,您正在尝试对不可变的 String 对象进行更改。 Simple way to achieve what you want is convert string to character array and loop over array items:
实现您想要的简单方法是将字符串转换为字符数组并遍历数组项:
Scanner input = new Scanner(System.in);
String data;
//prompt
System.out.println("Enter a sentence: ");
//input
data = input.nextLine();
char[] dataArray = data.toCharArray();
for (int i = 0; i < dataArray.length; i++) {
if (Character.isWhitespace(dataArray[i])) {
dataArray[i] = '+';
} else if (Character.isLowerCase(dataArray[i])) {
dataArray[i] = '?';
}
}
System.out.print(dataArray);
See the below code and figure out what's wrong in your code.查看下面的代码并找出您的代码中有什么问题。 To include multiple regex put the char within square brackets:
要包含多个正则表达式,请将字符放在方括号中:
import java.util.Scanner;
public class mainClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String data = input.nextLine();
String one = data.replaceAll(" ", "+");
String two = one.replaceAll("[a-z]", "?");
System.out.println(two);
}
}
You can do it in two steps by chaining String#replaceAll
.您可以通过链接
String#replaceAll
分两步完成。 In the first step, replace the regex, [az]
, with ?
在第一步中,将正则表达式
[az]
替换为?
. . The regex,
[az]
means a character from a
to z
.正则表达式
[az]
表示从a
到z
的字符。
public class Main {
public static void main(String[] args) {
String str = "I Like Java";
str = str.replaceAll("[a-z]", "?").replaceAll("\\s+", "+");
System.out.println(str);
}
}
Output:输出:
I+L???+J???
Alternatively , you can use a StringBuilder
to build the desired string.或者,您可以使用
StringBuilder
来构建所需的字符串。 Instead of using a StringBuilder
variable, you can use String
variable but I recommend you use StringBuilder
for such cases .您可以使用
String
变量而不是使用StringBuilder
变量,但我建议您在这种情况下使用StringBuilder
。 The logic of building the desired string is simple:构建所需字符串的逻辑很简单:
Loop through all characters of the string and check if the character is a lowercase letter.循环遍历字符串的所有字符并检查字符是否为小写字母。 If yes, append
?
如果是,附加
?
to the StringBuilder
instance else if the character is whitespace, append +
to the StringBuilder
instance else append the character to the StringBuilder
instance as it is.到
StringBuilder
实例,否则如果字符是空格,则将+
附加到StringBuilder
实例,否则将字符按原样附加到StringBuilder
实例。
Demo:演示:
public class Main {
public static void main(String[] args) {
String str = "I Like Java";
StringBuilder sb = new StringBuilder();
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (Character.isLowerCase(ch)) {
sb.append('?');
} else if (Character.isWhitespace(ch)) {
sb.append('+');
} else {
sb.append(ch);
}
}
// Assign the result to str
str = sb.toString();
// Display str
System.out.println(str);
}
}
Output:输出:
I+L???+J???
If the requirement states:如果要求规定:
?
?
. +
.+
。 you can do it as follows:你可以这样做:
Like the earlier solution, chain String#replaceAll
for two steps.与之前的解决方案一样,将
String#replaceAll
两个步骤。 In the first step, replace the regex, (?<=\\p{L})\\w
, with ?
在第一步中,将正则表达式
(?<=\\p{L})\\w
替换为?
. . The regex,
(?<=\\p{L})\\w
means:正则表达式
(?<=\\p{L})\\w
表示:
\\w
specifies a word character . \\w
指定一个单词 character 。(?<=\\p{L})
specifies a positive lookbeghind for a letter ie \\p{L}
. (?<=\\p{L})
指定一个字母的正向查找,即\\p{L}
。 In the second step, simply replace one or more whitespace characters ie \\s+
with +
.在第二步中,只需将一个或多个空白字符即
\\s+
替换为+
。
Demo:演示:
public class Main {
public static void main(String[] args) {
String str = "I like Java";
str = str.replaceAll("(?<=\\p{L})\\w", "?").replaceAll("\\s+", "+");
System.out.println(str);
}
}
Output:输出:
I+l???+J???
Alternatively , again like the earlier solution you can use a StringBuilder
to build the desired string.或者,再次像之前的解决方案一样,您可以使用
StringBuilder
来构建所需的字符串。 Loop through all characters of the string and check if the character is a letter.循环遍历字符串的所有字符并检查字符是否为字母。 If yes, append it to the
StringBuilder
instance and then loop through the remaining characters until all characters are exhausted or a space character is encountered.如果是,则将其附加到
StringBuilder
实例,然后循环遍历剩余的字符,直到用完所有字符或遇到空格字符。 If a whitespace character is encountered, append +
to the StringBuilder
instance else append ?
如果遇到空白字符,将
+
附加到StringBuilder
实例,否则附加?
to it.到它。
Demo:演示:
public class Main {
public static void main(String[] args) {
String str = "I like Java";
StringBuilder sb = new StringBuilder();
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i++);
if (Character.isLetter(ch)) {
sb.append(ch);
while (i < len && !Character.isWhitespace(ch = str.charAt(i))) {
sb.append('?');
i++;
}
if (Character.isWhitespace(ch)) {
sb.append('+');
}
}
}
// Assign the result to str
str = sb.toString();
// Display str
System.out.println(str);
}
}
Output:输出:
I+l???+J???
package com.company;
import java.util.*;
public class dat {
public static void main(String[] args) {
System.out.println("enter the string:");
Scanner ss = new Scanner(System.in);
String data = ss.nextLine();
for (int i = 0; i < data.length(); i++) {
char ch = data.charAt(i);
if (Character.isWhitespace(ch))
System.out.print("+");
else if (Character.isLowerCase(ch))
System.out.print("?");
else
System.out.print(ch);
}
}
}
enter the string:输入字符串:
i Love YouU
?+L???+Y??U
You can use String.codePoints
method to get a stream over int
values of characters of this string, and process them:您可以使用
String.codePoints
方法获取此字符串字符的int
值的流,并对其进行处理:
private static String replaceCharacters(String str) {
return str.codePoints()
.map(ch -> {
if (Character.isLowerCase(ch))
return '?';
if (Character.isWhitespace(ch))
return '+';
return ch;
})
.mapToObj(Character::toString)
.collect(Collectors.joining());
}
public static void main(String[] args) {
System.out.println(replaceCharacters("Lorem ipsum")); // L????+?????
System.out.println(replaceCharacters("I Like Java")); // I+L???+J???
}
See also: Replace non ASCII character from string另请参阅:替换字符串中的非 ASCII 字符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.