在String中按字符替换数字

时间:2015-07-07 18:01:36

标签: java regex char

我想用某些char替换ssn。例如:

public char filter = "a";
public String ssn = 123-45-6789
public replace(string ssn){
    //replace ssn = aaa-aa-aaaa because filter = "a"
}

任何人都可以告诉我如何做到这一点,因为它有" - "在字符串里面?

3 个答案:

答案 0 :(得分:3)

如果您只想更换数字,请尝试以下代码:

#include <iostream>
#include <memory>
#include <vector>

class Musician
{
    // Construction
    // ============

    public:
    template <typename T>
    Musician(const T& other) : m_concept(new Model<T>(other))
    {}

    Musician(const Musician& other) : m_concept(other.m_concept->copy())
    {}

    Musician(Musician&& x) = default;

    Musician& operator = (Musician other) {
        m_concept = std::move(other.m_concept);
        return *this;
    }

    // Duck Typing Interface
    // =====================

    public:
    // Enable generic functionality
    friend void play(Musician& musician) { musician.m_concept->play(); }
    // Invoke external functionality
    template <typename T> static void invoke_play(T& musician) { play(musician); }

    // Concept
    // =======

    private:
    struct Concept
    {
        virtual ~Concept() = default;
        virtual Concept* copy() = 0;
        virtual void play() = 0;
    };

    // Model
    // =====

    private:
    template <typename T>
    struct Model : Concept 
    {
        T object;

        Model(const T& other)
        : object(other) {}

        Concept* copy() override {
            return new Model(*this);
        }
        void play() override {
            invoke_play(object);
       }
    };

    private:
    std::unique_ptr<Concept> m_concept;
};


// Test
// ====

class Saxophonist {};
class Pianist {};
class Bassist {};
class Drummer {};

void play(Saxophonist&) { std::cout << "Saxophone\n"; }
void play(Pianist&) { std::cout << "Piano\n"; }
void play(Bassist&) { std::cout << "Bass\n"; }
void play(Drummer&) { std::cout << "Drum\n"; }

using JazzQuartet = std::vector<Musician>;
void play(JazzQuartet& quartet) {
    for (auto& musician : quartet)
        play(musician);
}

int main() {
    JazzQuartet quartet;
    quartet.emplace_back(Saxophonist());
    quartet.emplace_back(Pianist());
    quartet.emplace_back(Bassist());
    quartet.emplace_back(Drummer());
    play(quartet);
}

正则表达式public String replace(string ssn) { return ssn.replaceAll("[0-9]", "a"); } 定义应替换哪些字符(0到9之间的每个“字符”,意思是:只有数字)。

答案 1 :(得分:2)

要将regex与replaceAll()一起使用,您需要将过滤器设置为String。同样,您需要在replace函数中返回一个String。 请尝试以下方法:

String filter = "a";
public String replace(String ssn)
{
    return ssn.replaceAll("[0-9]",filter);
}

答案 2 :(得分:0)

您无法修改字符串,因为它是不可变类。但您可以使用替换值创建新字符串。所以

  • 创建StringBuidler
  • 遍历ssn的所有字符(toCharArray()在这里很有用)
    • 如果char是数字追加filter给构建者(Character.isDigit(char)会想到)
    • 如果char为-(或非数字),则'-'附加到构建器
  • 将构建器转换为String

您也可以尝试使用仅匹配数字的replaceAll和正则表达式。