简体   繁体   中英

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. Write the Java class to print a modified version of the String where all lowercase letters are replaced by ? and all whitespaces are replaced by + . An example is shown below: I Like Java becomes 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. 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 . In the first step, replace the regex, [az] , with ? . The regex, [az] means a character from a to 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. Instead of using a StringBuilder variable, you can use String variable but I recommend you use StringBuilder for such cases . 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.

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:

  1. The first character of each word is a letter (uppercase or lowercase) which needs to be left as it is.
  2. Second character onwards can be any word character which needs to be replaced with ? .
  3. All whitespace characters of the string need to be replaced with + .

you can do it as follows:

Like the earlier solution, chain String#replaceAll for two steps. In the first step, replace the regex, (?<=\\p{L})\\w , with ? . The regex, (?<=\\p{L})\\w means:

  1. \\w specifies a word character .
  2. (?<=\\p{L}) specifies a positive lookbeghind for a letter ie \\p{L} .

In the second step, simply replace one or more whitespace characters ie \\s+ with + .

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. 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. If a whitespace character is encountered, append + to the StringBuilder instance else append ? 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM