简体   繁体   中英

How to replace special characters in attributes of an object in JAVA

I have below class: in that i have attributes firstName and secondName which are type of String.

so i want to replace special characters in its attributes.

please have a look below code snippet.

public class Test {

    public static void main(String[] args) {

        Student student = new Student("T&st", "doing < and >");

        System.out.println("Student object   "+student);
        
        dataToProcess(student); // passing student object after replacing special charactes in its properties to dataToProcess()
        
    }
    private static void dataToProcess(Student student) {
        //other stuff
        //..........
    } 
}

class Student {

    String firstName;
    String lastName;

    public Student(String firstName, String lastName) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "Student(firstName=" + firstName + ", lastName=" + lastName + ")";
    }
    //Getters and Setters
}

here if i print Student i will get output as:

Student object
Student(firstName=T&st, lastName=doing < and >)

so i want to replace special character & with AAA and < with BBB and > with CCC in student's property such as fiestName and lastName

so final output would be: Student(firstName=TAAAst, lastName=doing BBB and CCC)

as you can see special characters are replaced

so please let me know how to do that?

NOTE: A class can have multiple attributes and an attribute can have multiple special characters.

Thanks//

You need to update the toString() in the Student class.

@Override
public String toString() {
    String newFirstName = firstName.replace("&","AAA");
    String newLastName = lastName.replace("<","BBB");
    newLastName = newLastName.replace(">","CCC");
    return "Student(firstName=" + newFirstName + ", lastName=" + newLastName + ")";
}

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