Displaying more than one String Array in Android - arrays

I am currently building an Book-App (sort of). So there are a lot of Strings, and the User can choose from which line he wants to start reading. So e.g there are 200 Strings in a String Array for Chapter one. And the User wants to start reading at Line 20(because he read the Lines before already). How can I display all the Strings from 20-200?
I have got:
Resources res = getResources();
String[] Book= res.getStringArray(R.array.ChapterOne);
TextView ChapterOne= (TextView) findViewById(R.id.Text);
SuraAlFateha.setText(Book[20]);
But This just diplays the Line 20. But I want it to Display All the Lines following from 20 (20-200).
How can I do this?
Thank you.

When you set the text you need to set all the text at once, like:
String resultString = '';
for ( int i = 20; i < Book.length; i++ )
resultString = resultString + "\n" + Book[i];
SuraAlFateha.setText( resultString.substring( 1 ) );
or something similar.
You should however calculate how much space you need and reserve it before starting the string appending or else your runtime and memory usage might get sky high.

Book[20] will simply give you the 20th element of the array, if you wish to get text for 20 through the end, you'll need to join the range of elements into a string.
You can use text and array utils to make this easy.
String joinedLines = TextUtils.join("\n", java.utils.Arrays.copyOfRange(Book, 20, Book.length));
SuraAlFateha.setText(joinedLines);

Related

How to convert 'inputdlg' output into text file?

I am writing a script that displays a character array (I would use a string array but inputdlg requires char), allows the user to edit the array, and outputs the new array into a text file.
However, I am running into the issue of not being able to format the output (vals1) into a text file. I think part of the problem is that the inputdlg command outputs a 1x1 array, which is difficult to convert back into the line-by-line format that I started with (in this case arr).
The code below outputs a single line read by column rather than row: "A1ReB2otC3bcD4e E5re 6tt 7 c 8S 9m i t h ". I'm not sure how I would convert this since the charvals1 (the inputdlg output) returns the same string of characters.
Is there a way to either return a row-by-row output (rather than the 1x1 array string) after the user inputs a new array, or print a reformatted version of the inputdlg output (including line breaks)?
arr = char(["ABCDE";
"123456789";
"Robert Smith";
"etc etc"])
% User updates the array
prompt = {'Update content below if necessary'};
dlgtitle = "Section 2";
dims = [30 50];
definput = {arr};
charvals1 = inputdlg(prompt,dlgtitle,dims,definput);
vals1 = convertCharsToStrings(charvals1);
% Outputting the updated array to text file
prompt = {'Enter desired input file name'};
dlgtitle = "Input Name";
dims = [1 35];
definput = {'Input Name'};
fileName = inputdlg(prompt,dlgtitle,dims,definput);
selected_dir = uigetdir();
fileLocation = char(strcat(selected_dir, '\', string(fileName(1)),'.txt'));
txtfile = fopen(fileLocation,'wt');
fprintf(txtfile, '%s\n', vals1) ;
Don't use convertCharsToStrings, since it will operate along the first dimension of the character array (you could transpose the character array first, but then the 'linebreaks' are lost).
You can convert the character array that you obtain to a string and then trim the whitespace. This can be written to a textfile without any problem with the code that you have already.
charvals1 = inputdlg(prompt,dlgtitle,dims,definput);
vals1 = string(charvals1{1}); % note the {1} to access the contents of the cell array.
vals1 = strtrim(vals1);
And don't forget to close the txtfile:
txtfile = fopen(fileLocation,'wt');
fprintf(txtfile, '%s\n', vals1);
fclose(txtfile);

How do I display strings from an array vertically stacked?

I am trying to take each string in my array and list them in a label one string per line. I tried using the joined method with /n to attempt to make it got to the next line but it just literally puts /n in between each string. I'm sorry if this happens to be a duplicate but unless I'm wording my question wrong I cant seem to find an answer. This is an example of what I'm looking for.
String[0]
String[1]
String[2]
and so on...
Try this:
let array = ["The", "quick", "brown", "fox"]
let string = array.joined(separator: "\n")
joined returns a new string by concatenating the elements of the sequence, adding the given separator (in this case, a line break) between each element in the array.
That will return this:
The
quick
brown
fox
...and set yourLabel.numberOfLines = 0
From Apple's documentation:
The default value for this numberOfLines is 1. To remove any maximum
limit, and use as many lines as needed, set the value of
numberOfLines to 0.
First make sure that the label can display multiple lines. If the UILabel is named lblText, then:
lblText.numberOfLines = 0
Then, simply use string interpolation to add in the line feeds:
lblText.text = "\(String[0])\n\(String[1])\n\(Stribng[2])"
The issue might be that you used "/n" instead of "\n" :)

How to create a new group of character array in matlab?

I have data stored in text files.The data is in 'cell array of string' after read it using textscan and contains various of colour name. Below is the content of my data:
name of colour
'lavender'
'lavenderblush'
'lemonchiffon'
'lightblue'
'lightcoral'
'lightcyan'
I want to create new array to group all color characters into the main color only (red, blue, orange, brown,etc).
I am really struggling to solve this problem. Thank you in advance for any help.
load_data = fopen('result.txt', 'r');
C = textscan(load_data, ' %s ');
fclose(load_data);
name = C{1,1};
group = char(name)
if group{:,1} == lavender
fprintf('purple');
else
fprintf('nothing');
end
This is my code but if I run this, always get error
Cell contents reference from a non-cell array object.
From your comment above, I assume you're having trouble with your code, not actually with the sorting of colors, or how to categorize them.
group is not a Cell array, it's a Char array. So in order to access its values you should use group(:,1) instead of group{:,1}
Remember that the number of columns in group is the number of characters in that line, normalized to the number of characters of the largest string in that set. So 2 issues here:
You can't use group(:,1), as it will get the first character of all the strings in that array. You should get the entire line for that string group(1,:). NB: I say string for simplicity, it's actually a char array.
'lavender' has only 10 characters, but it will have 15, as per the largest string. So the string comparison doesn't quite work, unless you add the extra blank spaces to compensate
You can try out the code below:
load_data = fopen('result.txt', 'r');
C = textscan(load_data, ' %s ');
fclose(load_data);
name = C{1,1};
if name{1,:} == '''lavender'''
fprintf('purple');
else
fprintf('nothing');
end
I assume that your TXT file actually has the string 'lavender', in this case I used character escape '''lavender'''.
The error you are getting is fairly clear. Once you have called char(name), you are working with a regular character array (i.e. a string) and no longer a cell array. Braces (i.e. {}) are used to index cell arrays so you should instead be using parentheses (i.e. ()). Note this actually happens as soon as you index using {} so C{1,1} would actually return a string already and the char line is thus redundant:
if group(:,1) == lavender
I suspect you actually want something more like
name = C{1};
group = char(name) %this line is redundant because C{1} already extracts a string
if strcmp(group,lavender)
fprintf('purple');
else
fprintf('nothing');
end
but it's impossible to say since you did not define the variable lavender.
I would also question what data structure you intend to use. I'm going to assume you actually have some way of categorizing the colours? I'm going to assume this is manual in which case I would suggest converting your txt file to a csv file and putting your manual colour categories as a second column but I'll leave the implementation details to you.
Lets say you have 3 colour categories for now, 'purple', 'blue', and 'orange', my suggestion is to use a logical matrix that has 3 columns (1 per colour category) and n rows where n is the number of rows in your text file (i.e. the number of colours you need to categorize).
Now I'm going to assume you have some sort of mapping function that can categorize your colours so map('lavender') returns 'purple' and map('lightcyan') returns 'blue'
First we should make a cell array of categories that we can use to map the category string to its column number:
categories = {'purple'
'blue'
'orange'}
and the result will go in the logical matrix categorized
load_data = fopen('result.txt', 'r');
C = textscan(load_data, ' %s ');
fclose(load_data);
n = numel(C);
categories = {'purple'
'blue'
'orange'};
categorized = false(n, numel(categories)); %preallocation
for row = 1:n
colour = C{row};
category = map(colour); %you need to implement this map function yourself.
categorized(row, strcmp(category, categories)) = true;
end

Have a string search set up in Matlab, how do I skip a string if none is found?

I have some data marked by a set of string markers that start with a 1 for the start, and a 2 for the end row of the data. These strings are a fixed list that I search from. If a string is not found, I want it to skip that string and just give the array a set of 0s as values. The code I use to search and break up the big data sheet into variables based on the markers is below:
tasknames = {'task1';'task2';'task3';'task4'};
for n = 1:numel(tasknames)
first = find(~cellfun(#isempty,strfind(Text(:,9),[tasknames{n},'_1'])))+1;
last = find(~cellfun(#isempty, strfind(Text(:,9),[tasknames{n},'_2'])))+1;
task_data{n} = Data(first:last, :);
end
Basically if strfnd comes back empty whne it goes to find that start and end row in Data, it crashes, because non exists. How do I avoid this crash and just fill task_data{n} for that particular marker with like 100 zeros or something?
If basically occurs when first and last are empty, meaning you can check it :
if(isempty(first)&&isempty(last))
task_data{n}=zeros(1,100);
else
task_data{n}= Data(first:last, :);
end

Apply a string value to several positions of a cell array

I am trying to create a string array which will be fed with string values read from a text file this way:
labels = textread(file_name, '%s');
Basically, for each string in each line of the text file file_name I want to put this string in 10 positions of a final string array, which will be later saved in another text file.
What I do in my code is, for each string in file_name I put this string in 10 positions of a temporary cell array and then concatenate this array with a final array this way:
final_vector='';
for i=1:size(labels)
temp_vector=cell(1,10);
temp_vector{1:10}=labels{i};
final_vector=horzcat(final_vector,temp_vector);
end
But when I run the code the following error appears:
The right hand side of this assignment has too few values to satisfy the left hand side.
Error in my_example_code (line 16)
temp_vector{1:10}=labels{i};
I am too rookie in cell strings in matlab and I don't really know what is happening. Do you know what is happening or even have a better solution to my problem?
Use deal and put the left hand side in square brackets:
labels{1} = 'Hello World!'
temp_vector = cell(10,1)
[temp_vector{1:10}] = deal(labels{1});
This works because deal can distribute one value to multiple outputs [a,b,c,...]. temp_vector{1:10} alone creates a comma-separated list and putting them into [] creates the output array [temp_vector{1}, temp_vector{2}, ...] which can then be populated by deal.
It is happening because you want to distribute one value to 10 cells - but Matlab is expecting that you like to assign 10 values to 10 cells. So an alternative approach, maybe more logic, but slower, would be:
n = 10;
temp_vector(1:n) = repmat(labels(1),n,1);
I also found another solution
final_vector='';
for i=1:size(labels)
temp_vector=cell(1,10);
temp_vector(:,1:10)=cellstr(labels{i});
final_vector=horzcat(final_vector,temp_vector);
end

Resources