Change all indices of a word in a string to '*'.

3 Ansichten (letzte 30 Tage)
Bob Whiley
Bob Whiley am 3 Mär. 2015
Kommentiert: Joseph Cheng am 3 Mär. 2015
What is the best method to change all indices of a certain word in a string to '*'.
Like if my string were 'Hello, my name is bob, my age is 43.' And I want to change bob and age so it outputs 'Hello, my name is ***, my *** is 43.'

Antworten (1)

Guillaume
Guillaume am 3 Mär. 2015
Bearbeitet: Guillaume am 3 Mär. 2015
str = 'Hello, my name is bob, my age is 43.';
regexprep(str, 'bob|age', '***')
  1 Kommentar
Joseph Cheng
Joseph Cheng am 3 Mär. 2015
to expand on Guillaume's answer, since names are probably not going to stay 3 char long.
you can get the position and items using regexp:
filters = {'bob'; 'age'}';
teststr = 'Hello, my name is bob, my age is 43.';
regpattern = sprintf(strjoin(filters, '|'));
matches = regexp(teststr, regpattern, 'match')
pos= regexp(teststr, regpattern)
then knowing what was matched and where the positions are you can replace those index positions with "*".

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by