MATLAB: Remove everything after the final blank in a character array - matlab

How can I remove all characters after the final blank in a character array?
Input:
ch = {'Test1 Index'; 'Test 2 Index'; 'Test 3 4 Curncy'}
Expected Output:
ch = {'Test1'; 'Test 2'; 'Test 3 4'}

From your example it seems that you want to remove all characters after the final blank, and remove that final blank too.
You can use regexrep as follows:
result = regexprep(ch, '\s\S*$', '');
The regular expression '\s\S*$' matches a blank (\s) followed by zero or more non-blanks (\S*) up to the end of the string ($). The matched substring is replaced by the empty string ('').

Related

How to trim leading and trailing spaces from a string in flutter

I have a 'textformfeild' that takes strings and I want to trim the white spaces at the begining and the end and strict the one in the middle to only one space.
for example if my string is like this:(....AB....CD.....) where the black dots represent the white spaces.
and I wanna make it look like this:(AB.CD)
any idea on how to do that?
this is what I tried to do:
userWeight!.trim()
but this will remove all the white spaces including the one in the middle
trim will remove left and right spaces. You can use RegExp to remove inner spaces:
void main(List<String> args) {
String data = " AB CD ";
String result = data.trim().replaceAll(RegExp(r' \s+'), ' ');
print(result); //AB CD
}
Trim - If you use trim() this will remove only first and end of the white spaces example,
String str1 = " Hello World ";
print(str1.trim());
The output will be only = Hello World
For your purpose you may use replaceAll
String str1 = "....AB....CD.....";
print(str1.replaceAll("....","."));
The output will be = ".AB.CD."
If you still want to remove first and last . use substring
String str1 = "....AB....CD.....";
print(str1.replaceAll("....",".").substring( 1, str1.length() - 1 ));
The output will be = "AB.CD"
This is what your expected output is.
Trim will remove white spaces before and after the string..
Trim will only remove the leading and trailing spaces or white space characters of a given string
Refer this for more:
https://api.flutter.dev/flutter/dart-core/String/trim.html
String str = " AB CD ";
str = str.trim();
while (str.contains(" ")) {
str = str.replaceAll(" ", " ");
}
print(str);

How to replace 2 spaces middle of string to a character and a space in Dart?

I have string as shown below. In dart replaceFirst() its removes all whitespace and it's not what i want. My question is: How to replace 2 spaces middle of string to a character and a space in Dart?
Example:
- Original: String _myText = "abc 23";
- Expected Text: "abcd 23"
- Result with replaceFirst() : "abcd23"
"abc 23".replaceFirst(' ', 'd') returns the expected output.
Use wrap widget may be your problem would be solve
Eg:
Wrap( child:Text(“hii Byy”))
Use below code
String _myText = "abc 23";
_myText.replaceAll(' ', ' '); // it returns the string 'abc 23'
"abc 23".replaceFirst(' ', 'd') returns the expected output. Are you sure, you pass a single white space character and not two as the first parameter of the replaceFirst method ?

Swift String including Special Characters

I have a user enter a multi string in an NSTextView.
var textViewString = textView.textStorage?.string
Printing the string ( print(textViewString) ), I get a multi-line string, for example:
hello this is line 1
and this is line 2
I want a swift string representation that includes the new line characters. For example, I want print(textStringFlat) to print:
hello this is line 1\n\nand this is line 2
What do I need to do to textViewString to expose the special characters?
If you just want to replace the newlines with the literal characters \ and n then use:
let escapedText = someText.replacingOccurrences(of: "\n", with: "\\n")

Counting sentences *not* lines of a text file

For an assignment I need to find the number of sentences of a text file (not the lines). That means at the end of string I will have '.' or '!' or '?'. After struggling a lot I wrote a code, which is giving an error. I do not see any mistake though. If anyone can help me, that will be highly appreciated. Thanks
Here is my code
fh1 = fopen(nameEssay); %nameEssay is a string of the name of the file with .txt
line1 = fgetl(fh1);
% line1 gives the title of the essay. that is not counted as a sentence
essay = [];
line = ' ';
while ischar(line)
line =fgetl(fh1);
essay = [essay line];
%creates a long string of the whole essay
end
sentenceCount=0;
allScore = [ ];
[sentence essay] = strtok(essay, '.?!');
while ~isempty(sentence)
sentenceCount = sentenceCount + 1;
sentence = [sentence essay(1)];
essay= essay(3:end); %(1st character is a punctuation. 2nd is a space.)
while ~isempty(essay)
[sentence essay] = strtok(essay, '.?!');
end
end
fclose(fh1);
regexp handles this nicely:
>> essay = 'First sentence. Second one? Third! Last one.'
essay =
First sentence. Second one? Third! Last one.
>> sentences = regexp(essay,'\S.*?[\.\!\?]','match')
sentences =
'First sentence.' 'Second one?' 'Third!' 'Last one.'
In the pattern '\S.*?[\.\!\?]', the \S says a sentence starts with a non-whitespace character, the .*? matches any number of characters (non-greedily), until a punctuation marking the end of a sentence ([\.\!\?]) is encountered.
If you count number of senteces, based on '.' or '!' or '?', you can just calculate the number of these characters in essey. Thus, if essay is array containing characters you can do:
essay = 'Some sentece. Sentec 2! Sentece 3? Sentece 4.';
% count number of '.' or '!' or '?' in essey.
sum(essay == abs('.'))
sum(essay == abs('?'))
sum(essay == abs('!'))
% gives, 2, 1, 1. Thus there are 4 sentences in the example.
If you want senteces, you can use strsplit as Dan suggested, e.g.
[C, matches] = strsplit(essay,{'.','?', '!'}, 'CollapseDelimiters',true)
% gives
C =
'Some sentece' ' Sentec 2' ' Sentece 3' ' Sentece 4' ''
matches =
'.' '!' '?' '.'
And calculate the number of elements in matches. For the example last element is empty. It can be filtered out easly.

print cells type in Matlab

I have a cell array like:
>>text
'Sentence1'
'Sentence2'
'Sentence3'
Whenever I use
sprintf(fid,'%s\n',text)
I get an error saying:
'Function is not defined for 'cell' inputs.'
But if I put :
sprintf(fid,'%s\n',char(text))
It works but in the file appears all the sentences mixed all together like with no sense.
Can you recommend me what to do?
Whener I put text I get:
>>text
'Title '
'Author'
'comments '
{3x1} cell
That is why I can not use text{:}.
If you issue
sprintf('%s\n', text)
you are saying "print a string with a newline. The string is this cell array". That's not correct; a cell-array is not a string.
If you issue
sprintf('%s\n', char(text))
you are saying "print a string with a newline. The string is this cell array, which I convert to character array.". The thing is, that conversion results in a single character array, and sprintf will re-use the %s\n format only for multiple inputs. Moreover, it writes that single character array by column, meaning, all characters in the first column, concatenated horizontally with all characters from the second column, concatenated with all characters from the third column, etc.
Therefore, the approprate call to sprintf is something with multiple inputs:
sprintf(fid, '%s\n', text{:})
because the cell-expansion text{:} creates a comma-separated list from all entries in the cell-array, which is exactly what sprintf/fprintf expects.
EDIT As you indicate:, you have non-char entries in text. You have to check for that. If you want to pass only the strings into fprintf, use
fprintf(fid, '%s\n', text{ cellfun('isclass', text, 'char') })
if that {3x1 cell} is again a set of strings, so you want to write all strings recursively, then just use something like this:
function textWriter
text = {...
'Title'
'Author'
'comments'
{...
'Title2'
'Author2'
'comments2'
{...
'Title3'
'Author3'
'comments3'
}
}
}
text = cell2str(text);
fprintf(fid, '%s\n', text{:});
end
function out = cell2str(c)
out = {};
for ii = c(:)'
if iscell(ii{1})
S = cell2str(ii{1});
out(end+1:end+numel(S)) = S;
else
out{end+1} = ii{1};
end
end
end