How to display each individual word of a string in MATLAB - string

How to display each individual word of a string in MATLAB version R2012a? The function strsplit doesn't work in this version. For example 'Hello, here I am'. I want to display every word on a single line.

Each word in a single line means replacing each blank with a new line:
strrep(s,' ',sprintf('\n'))

You can use regexp with the 'split' option:
>> str = 'Hello, here I am';
>> words = regexp(str, '\s+', 'split').'
words =
'Hello,'
'here'
'I'
'am'
Change '\s+' to a more elaborate pattern if needed.

Related

How to use .replace() properly

I am trying to remove "--" from words. For example, the word "World--fourthousand" should be replaced with white space doing string.replace('--', ' ')
String.replace('--', ' ') I have already tried and doesn't remove it.
if "--" in string:
string.replace("--", " ")
Expected "World fourthousand"
Actual "World--fourthousand"
replace returns a new string with the substring replaced, it doesn't alter the original string. So you could do:
string = string.replace("--"," ")
The replace() function should return a copy of the string with the intended characters replaced. That being said, I believe you should assign the result of the replace function into another variable, which will hold the desired value.
if "--" in string:
new_string = string.replace("--", " ")
Strings are what you call immutable objects, which means that whenever you modify them, you get a new object, and the original string is intact, so you would need to save the edited string in a new variable like so:
s = "World--fourthousand"
s = s.replace("--"," ")
print(s)
#World fourthousand
From the docs: https://docs.python.org/3/library/string.html#string.replace
Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

How to split string using a whole word as separator?

Is there a way to split string like:
"importanttext1 has gathered importanttext2 from stackoverflow."
I want to grab anything before the word "has", and just want to grab the one word after "gathered", so it doesn't include "from stackoverflow.". I want to be left with 2 variables that cointain importanttext1 and importanttext2
local str = "importanttext1 has gathered importanttext2 from stackoverflow."
local s1 = str:match("(.+)has")
local s2 = str:match("gathered%s+(%S+)")
print(s1)
print(s2)
Note that "%s" matches a whitespace character while "%S" matches a non-whitespace character.

split a string delimited by given object type

How can I split a string into a list of substrings, where the delimiter to split by is a MATLAB object type?
For example:
>> splitByType('a1b2c3',type=integer)
['a','b','c']
or:
>> splitByType('a1b2c3',type=character)
['1','2','3']
I'm not sure what you mean by MATLAB object type. For integers, you can use:
a='a1b2c'
regexp(a,'[0-9]+','split')
which outputs:
ans =
'a' 'b' 'c'
Another alternative is:
regexp(a,'\d+','split')
You're looking for regexp() by passing the corresponding regular expression of the type:
For integers: regexp('a1b2c','\d+','split') % or use '[0-9]+'
For characters: regexp('a1b2c','[a-z]+','split')
I'd go with the regexp answer, if you are comfortable with regular expressions, but you can also use strsplit with a cell array of strings containing the possible delimiters:
strsplit(a,cellstr(num2str((0:9)'))') % digits
strsplit(a,cellstr(char([65:90 97:122])')') % word characters
Also, strsplit has a regular expression mode (bizarre! why would you use this over regexp?):
strsplit(a,'\d+','delim','reg') % one or more digits
strsplit(a,'\w+','delim','reg') % one or more word characters
Which are equivalent to regexp(a,'\d+','split') and regexp(a,'\w+','split').

Finding mean of ascii values in a string MATLAB

The string I am given is as follows:
scrap1 =
a le h
ke fd
zyq b
ner i
You'll notice there are 2 blank spaces indicating a space (ASCII 32) in each row. I need to find the mean ASCII value in each column without taking into account the spaces (32). So first I would convert to with double(scrap1) but then how do I find the mean without taking into account the spaces?
If it's only the ASCII 32 you want to omit:
d = double(scrap1);
result = mean(d(d~=32)); %// logical indexing to remove unwanted value, then mean
You can remove the intermediate spaces in the string with scrap1(scrap1 == ' ') = ''; This replaces any space in the input with an empty string. Then you can do the conversion to double and average the result. See here for other methods.
Probably, you can use regex to find the space and ignore it. "\s"
findSpace = regexp(scrap1, '\s', 'ignore')
% I am not sure about the ignore case, this what comes to my mind. but u can read more about regexp by typying doc regexp.

Convert underscores to spaces in Matlab string?

So say I have a string with some underscores like hi_there.
Is there a way to auto-convert that string into "hi there"?
(the original string, by the way, is a variable name that I'm converting into a plot title).
Surprising that no-one has yet mentioned strrep:
>> strrep('string_with_underscores', '_', ' ')
ans =
string with underscores
which should be the official way to do a simple string replacements. For such a simple case, regexprep is overkill: yes, they are Swiss-knifes that can do everything possible, but they come with a long manual. String indexing shown by AndreasH only works for replacing single characters, it cannot do this:
>> s = 'string*-*with*-*funny*-*separators';
>> strrep(s, '*-*', ' ')
ans =
string with funny separators
>> s(s=='*-*') = ' '
Error using ==
Matrix dimensions must agree.
As a bonus, it also works for cell-arrays with strings:
>> strrep({'This_is_a','cell_array_with','strings_with','underscores'},'_',' ')
ans =
'This is a' 'cell array with' 'strings with' 'underscores'
Try this Matlab code for a string variable 's'
s(s=='_') = ' ';
If you ever have to do anything more complicated, say doing a replacement of multiple variable length strings,
s(s == '_') = ' ' will be a huge pain. If your replacement needs ever get more complicated consider using regexprep:
>> regexprep({'hi_there', 'hey_there'}, '_', ' ')
ans =
'hi there' 'hey there'
That being said, in your case #AndreasH.'s solution is the most appropriate and regexprep is overkill.
A more interesting question is why you are passing variables around as strings?
regexprep() may be what you're looking for and is a handy function in general.
regexprep('hi_there','_',' ')
Will take the first argument string, and replace instances of the second argument with the third. In this case it replaces all underscores with a space.
In Matlab strings are vectors, so performing simple string manipulations can be achieved using standard operators e.g. replacing _ with whitespace.
text = 'variable_name';
text(text=='_') = ' '; //replace all occurrences of underscore with whitespace
=> text = variable name
I know this was already answered, however, in my case I was looking for a way to correct plot titles so that I could include a filename (which could have underscores). So, I wanted to print them with the underscores NOT displaying with as subscripts. So, using this great info above, and rather than a space, I escaped the subscript in the substitution.
For example:
% Have the user select a file:
[infile inpath]=uigetfile('*.txt','Get some text file');
figure
% this is a problem for filenames with underscores
title(infile)
% this correctly displays filenames with underscores
title(strrep(infile,'_','\_'))

Resources