Is it possible to build a list from a carriage return separated string? - flutter

Background
I have the following string:
var MyString = 'Test1⏎Test2⏎Test3⏎Test4'
⏎ = line feed = \n
What I'm trying to do
I want to create a List which is a list of lines. Basically every item that is followed by a \n would become an entry in the list.
I want the base string MyString to become shortened to reflect what pieces of the string have been moved to the List
The reason I want to leave a residual MyString is that new data might come in later that might be considered part of the same line, so I do not want to commit the data to the List until there is a carriage return seen
What the result of all this would be
So in my above example, only Test1 Test2 Test3 are followed by \n but not Test4
Output List would be: [Test1, Test2, Test3]
MyString would become: Test4
What I've tried and failed with
I tried using LineSplitter but it seems to want to take Test4 as a separate entry as well
final lines = const LineSplitter().convert(MyString);
for (final daLine in lines) {
MyList.add(daLine);
}
And it creates [Test1, Test2, Test3, Test4]

A solution would be to just .removeLast() on the list that you split.
String text = 'Test1\nTest2\nTest3\nTest4';
List<String> list = text.split('\n');
text = list.removeLast();
print(list); // [Test1, Test2, Test3]
print(text); // Test4

To me you are combining two questions. Every language I know has built-in ways to split a string on a char, including newline chars. The distinct thing you want is a split function that doesn't include the last entry.
You may be combining your answers as well :) Is there some resource constraint or streamed input that prevents you from just building the list, then popping off the final entry?
If yes:
I think you have to build your own split. Look at the implementation code for LineSplitter(), and make something similar except which leaves the final entry.
If no:
simply call
MyString = MyList.removeLast();
after your for-loop.

Related

Converting numbers into timestamps (inserting colons at specific places)

I'm using AutoHotkey for this as the code is the most understandable to me. So I have a document with numbers and text, for example like this
120344 text text text
234000 text text
and the desired output is
12:03:44 text text text
23:40:00 text text
I'm sure StrReplace can be used to insert the colons in, but I'm not sure how to specify the position of the colons or ask AHK to 'find' specific strings of 6 digit numbers. Before, I would have highlighted the text I want to apply StrReplace to and then press a hotkey, but I was wondering if there is a more efficient way to do this that doesn't need my interaction. Even just pointing to the relevant functions I would need to look into to do this would be helpful! Thanks so much, I'm still very new to programming.
hfontanez's answer was very helpful in figuring out that for this problem, I had to use a loop and substring function. I'm sure there are much less messy ways to write this code, but this is the final version of what worked for my purposes:
Loop, read, C:\[location of input file]
{
{ If A_LoopReadLine = ;
Continue ; this part is to ignore the blank lines in the file
}
{
one := A_LoopReadLine
x := SubStr(one, 1, 2)
y := SubStr(one, 3, 2)
z := SubStr(one, 5)
two := x . ":" . y . ":" . z
FileAppend, %two%`r`n, C:\[location of output file]
}
}
return
Assuming that the "timestamp" component is always 6 characters long and always at the beginning of the string, this solution should work just fine.
String test = "012345 test test test";
test = test.substring(0, 2) + ":" + test.substring(2, 4) + ":" + test.substring(4, test.length());
This outputs 01:23:45 test test test
Why? Because you are temporarily creating a String object that it's two characters long and then you insert the colon before taking the next pair. Lastly, you append the rest of the String and assign it to whichever String variable you want. Remember, the substring method doesn't modify the String object you are calling the method on. This method returns a "new" String object. Therefore, the variable test is unmodified until the assignment operation kicks in at the end.
Alternatively, you can use a StringBuilder and append each component like this:
StringBuilder sbuff = new StringBuilder();
sbuff.append(test.substring(0,2));
sbuff.append(":");
sbuff.append(test.substring(2,4));
sbuff.append(":");
sbuff.append(test.substring(4,test.length()));
test = sbuff.toString();
You could also use a "fancy" loop to do this, but I think for something this simple, looping is just overkill. Oh, I almost forgot, this should work with both of your test strings because after the last colon insert, the code takes the substring from index position 4 all the way to the end of the string indiscriminately.

Flutter remove whitespace, commas, and brackets from List when going to display as a String

I want to go through my list of strings, and add it to a text element for display, but I want to remove the commas and remove the [] as well as the whitespace, but leave the symbols except the commas and brackets.
So if the List is.
[1,2,#3,*4,+5]
In the text field I want it to show - "12#3*4+5"
I can figure out how to display it, but Im using
Text(myList.tostring().replaceAll('[\\]\\,\\', '')
Is there a way to do this?
You should use the reduce method on your list.
List<String> myList = ["1", "2", "#3", "*4", "+5"];
String finalStr = myList.reduce((value, element) {
return value + element;
});
print(finalStr);
# output: "12#3*4+5"
This method reduces a collection to a single value by iteratively combining elements of the collection using the provided function.
The method takes a function that receives two parameters: one is the current concatenated value, which starts out with the value of the first element of your list, and the second parameter is the next element on your list. So you can do something with those two values, and return it for the next iterations. At last, a single reduced value is returned. In this case, using strings, the code in my answer will concatenate the values. If those were numbers, the result would be a sum of the elements.
If you want to add anything in between elements, simply use the return value. For instance, to separate the elements by comma and whitespace, it should look like return value + " ," + element;.
Unless I'm misunderstanding the question, the most obvious solution would be to use List.join().
List<String> myList = ["1", "2", "#3", "*4", "+5"];
print( myList.join() );
// Result
// 12#3*4+5
You could also specify a separator
print( myList.join(' ') );
// Result
// 1 2 #3 *4 +5

Adding new line to NSCharacterSet

I want to strip a string of all new lines and commas (and place it into an array), so I created this:
let results = text.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: ",\n"))
However, the newlines are still existing in my array (the commas are being removed). What's the correct way of adding newline to the NSCharacterSet? Or, how to add comma to NSCharacterSet.newLineCharacterSet.
Thanks.
Here is janky solution, but still looking for a more elegant one.
var results = text.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: ","))
text = results.joinWithSeparator(" ")
results = text.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
(one-line) SOLUTION:
var results = text.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: " ,\u{000A}\u{000B}\u{000C}\u{000D}\u{0085}"))
Explanation is below.
You can unite two NSCharacterSet by first using an NSMutableCharacterSet, for example:
let charset = NSMutableCharacterSet(charactersInString: ",")
charset.formUnionWithCharacterSet(NSCharacterSet.newlineCharacterSet())
let results = text.componentsSeparatedByCharactersInSet(charset)
So MartinR brought to my attention that there are more line feeds than just "\n".
I looked at the values used in NSCharacterSet.newlineCharacterSet and added them all, giving me:
var results = text.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: " ,\u{000A}\u{000B}\u{000C}\u{000D}\u{0085}"))
This got rid of all the whitespace, commas, and new lines. Interestingly - when I used all the newline values separately to see if I could figure out which newline was being used in my case, none of them worked. But when used all together, it strips my new lines.

Getting IndexOutOfBounds Exception while search for a subtring

I have a string like
var word = "banana"
and a sentence like var sent = "the monkey is holding a banana which is yellow"
sent1 = "banana!!"
I want to search banana in sent and then write to a file in the following way:
the monkey is holding a
banana
which is yellow
I'm doing it in the following way:
var before = sent.substring(0, sent.indexOf(word))
var after = sent.substring(sent.indexOf(word) + word.length)
println(before)
println(after)
This works fine but when I do the same for sent1, then it gives me IndexOutOfBoundsException. I think it is because there is nothing before banana in sent1. How to deal with this?
You can split based on the word and you will get an array with everything before and after the word.
val search = sent.split(word)
search: Array[String] = Array("the monkey is holding a ", " which is yellow")
This works in the "banana!!!" case:
"banana!!".split(word)
res5: Array[String] = Array("", !!)
Now you can write the three lines to a file in your favorite way:
println(search(0))
println(word)
println(search(1))
What if you had more than one occurrence of the word? .split understands regular expressions, so you could improve the previous solution with something like this:
string
.replaceAll("\\s+(?=banana)|(?<=banana)\\s+")
.foreach(println)
\\s means a whitespace character
(?=<word>) means "followed by <word>"
(?<=<word>) means "preceded by <word>"
So, this would split your string into pieces, using any spaces either preceded or followed by the "banana", and not the word itself. The actual word ends up in the list, just like the other parts of the string, so you don't need to print it out explicitly
This regex trick is called "positive look-around" ( ?= is look-ahead, ?<= is look-behind) in case you are wondering.

printing a vector of string in static text box with new lines

I have a bunch of classes that I am iterating through and collecting which classes the student is failing in. If the student fails , I collect the name of the class in a vector called retake.
retake =[Math History Science]
I have line breaks so when the classes print in the command window it shows as:
retake=
Math
History
Science.
However, I am trying display retake in a static text box in Gui Guide so it looks like the above. Instead, the static text box is showing as:
MathHistoryScience
set(handles.text13,'String', retake) % this is what I tried
can you please show me so it prints:
Math
History
Science
It looks to me like you need to add carriage returns.
Assuming you have a cell array with strings (rather than concatenated strings using [], which will give you a single long line), you can do it as follows:
retake = {'Math', 'History', 'Science'};
rString = '';
for ii = 1:numel(retake)-1
rString = [rString sprintf('%s\n', retake{ii}];
end
rString = [rString retake{end}];
Notice the use of '' to denote strings, {} to denote a cell array, '\n' as the end-of-line character, and [a b] to do simple string concatenation.