Flutter String Concatenation breaking when last string is file extension - string

I'm trying to concatenate some strings which will eventually be part of a URL, but the result of the concatenation is always missing the last String which is a file extension.
I've tried all the official ways of concatenating. Here is my latest attempt when I tried to merge the strings by using the join method on a String List.
String? resColor = color?.label;
String? resCategory = category?.label;
print(resColor!.length);
List<String> refSplit = [
'previewAssets/',
resCategory!,
'/',
resColor!,
'.jpg'
];
for (int i = 0; i < refSplit.length; i++) {
print(refSplit[i]);
}
String ref = refSplit.join('');
print(refSplit);
print(ref);
My excepted outcome is obviously that ref would contain all items from refSplit. But it doesn't.
Here is the output from the prints: output
Im knida new to flutter but I feel like concatenating strings shouldn't be this hard, so I'm probably missing something obvious. Any help would be greatly appreciated.
*edit: So I've continued to look into this and I'm pretty sure the problem is with resColor, which suspiciously has a length of 4 when it should be 3. So my current guess is that it contains some invisible endline like char at the end which is messing up the concat.
**edit: By removing the last char of resColor, it fixed the issue. This is the code I used to do that: resColor = resColor!.substring( 0, resColor!.length -1);

I tried your code and it seems to work fine in dartpad
void main() {
List<String> refSplit = [
'previewAssets/',
'something',
'/',
'109',
'.jpg'
];
String ref = refSplit.join("");
print(ref);
}
Try to restart your IDE and try again.

Related

Making sure every Alphabet is in a string (Kotlin)

So I have a question where I am checking if a string has every letter of the alphabet in it. I was able to check if there is alphabet in the string, but I'm not sure how to check if there is EVERY alphabet in said string. Here's the code
fun isPangram (pangram: Array<String>) : String {
var panString : String
var outcome = ""
for (i in pangram.indices){
panString = pangram[i]
if (panString.matches(".^*[a-z].*".toRegex())){
outcome = outcome.plus('1')
}
else {outcome = outcome.plus('0')}
}
return outcome
}
Any ideas are welcomed Thanks.
I think it would be easier to check if all members of the alphabet range are in each string than to use Regex:
fun isPangram(pangram: Array<String>): String =
pangram.joinToString("") { inputString ->
when {
('a'..'z').all { it in inputString.lowercase() } -> "1"
else -> "0"
}
}
Hi this is how you can make with regular expression
Kotlin Syntax
fun isStrinfContainsAllAlphabeta( input: String) {
return input.lowercase()
.replace("[^a-z]".toRegex(), "")
.replace("(.)(?=.*\\1)".toRegex(), "")
.length == 26;
}
In java:
public static boolean isStrinfContainsAllAlphabeta(String input) {
return input.toLowerCase()
.replace("[^a-z]", "")
.replace("(.)(?=.*\\1)", "")
.length() == 26;
}
the function takes only one string. The first "replaceAll" removes all the non-alphabet characters, The second one removes the duplicated character, then you check how many characters remained.
Just to bounce off Tenfour04's solution, if you write two functions (one for the pangram check, one for processing the array) I feel like you can make it a little more readable, since they're really two separate tasks. (This is partly an excuse to show you some Kotlin tricks!)
val String.isPangram get() = ('a'..'z').all { this.contains(it, ignoreCase = true) }
fun checkPangrams(strings: Array<String>) =
strings.joinToString("") { if (it.isPangram) "1" else "0" }
You could use an extension function instead of an extension property (so it.isPangram()), or just a plain function with a parameter (isPangram(it)), but you can write stuff that almost reads like English, if you want!

Get the first line of a string in haxe

Let's assume we have a multiline string, like
var s:String = "my first line\nmy second line\nmy third line\nand so on!";
What is the best way to get (only) the first line of this string in Haxe? I know I can do something like:
static function getFirstLine(s:String):String {
var t:String = s.split("\n")[0];
if(t.charAt(t.length - 1) == "\r") {
t = t.substring(0, t.length - 1);
}
return t;
}
However I'm wondering if there is any easier (predefined) method for this ...
Caveat that #Gama11's answer works well and is more elegant than this.
If your string is long, split will iterate over the whole thing and allocate an array containing every line in your string, both of which are unnecessary here. Another option would be indexOf:
static function getFirstLine(s:String):String {
var i = s.indexOf("\n");
if (i == -1) return s;
if (i > 0 && s.charAt(i - 1) == "\r") --i;
return s.substr(0, i);
}
There's no built-in utility in the standard library for this that I know of, but you make it a bit more elegant and avoid the substring() handling for \r by splitting on a regex:
static function getFirstLine(s:String):String {
return ~/\r?\n/.split(s)[0];
}
The regex \r?\n optionally matches a carriage return followed by a line feed character.

Node.JS string array sort is not working

Hi I am absolute beginner of node.js Today I tried the following code
var fs, arr;
var dir, str;
var cont, item;
fs=require('fs');
cont=fs.readFileSync('unsort.txt').toString();
arr=cont.split('\n');
arr.sort();
for(str=arr.shift();str&&(item=arr.shift());)
str+='\n'+item;
fs.writeFileSync('sort_by_script.txt', str);
the above node.js code reads a file as string, from the directory of the node.exe. Splits the string by newline ('\n') to get a array. Sorts the array and prints the sorted array to the file. So as a whole the script reads a file sort the entries and saves the sorted entry in another file. The problem is the sorted order is not correct. I tried sorting the content of unsort.txt manually using MS Excel by which I got the correct order of sort. Can any one help me why the arr.sort() is not working correct. You can download unsort.txt, sort_by_script.txt, sort_by_ms_excel.txt and node.exe in the package [Sort.rar][1]
Note : unsort.txt has no numbers. All are only alphabets.
Examples from unsort.txt:
appjs
gbi
node
frame
require
process
module
WebSocket
webkitAudioContext
webkitRTCPeerConnection
webkitPeerConnection00
webkitMediaStream
MediaController
HTMLSourceElement
TimeRanges
If you do not pass a custom search function the sort function sorts lexically, numbers get cast to strings and so it happens that e.g. "10" is before "3". So the strings get sorted.
You can pass a custom function to the sort function which decides the order of the items, in case of numbers this would be an example (Be careful as numbers in your example would be strings if you dont cast / parse them to numbers) :
var numsort = function (a, b) {
return a - b;
}
var numbers = new Array(20, 2, 11, 4, 1);
var result = numbers.sort(numsort);
Another example for strings:
var sortstring = function (a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
if (a < b) return 1;
if (a > b) return -1;
return 0;
}
I would use
arr.sort((obj1, obj2) => {
return obj1.localeCompare(obj2);
});
That will most likely solve your issue.

C++/CLI - Split a string with a unknown number of spaces as separator?

I'm wondering how (and in which way it's best to do it) to split a string with a unknown number of spaces as separator in C++/CLI?
Edit: The problem is that the space number is unknown, so when I try to use the split method like this:
String^ line;
StreamReader^ SCR = gcnew StreamReader("input.txt");
while ((line = SCR->ReadLine()) != nullptr && line != nullptr)
{
if (line->IndexOf(' ') != -1)
for each (String^ SCS in line->Split(nullptr, 2))
{
//Load the lines...
}
}
And this is a example how Input.txt look:
ThisISSomeTxt<space><space><space><tab>PartNumberTwo<space>PartNumber3
When I then try to run the program the first line that is loaded is "ThisISSomeTxt" the second line that is loaded is "" (nothing), the third line that is loaded is also "" (nothing), the fourth line is also "" nothing, the fifth line that is loaded is " PartNumberTwo" and the sixth line is PartNumber3.
I only want ThisISSomeTxt and PartNumberTwo to be loaded :? How can I do this?
Why not just using System::String::Split(..)?
The following code example taken from http://msdn.microsoft.com/en-us/library/b873y76a(v=vs.80).aspx#Y0 , demonstrates how you can tokenize a string with the Split method.
using namespace System;
using namespace System::Collections;
int main()
{
String^ words = "this is a list of words, with: a bit of punctuation.";
array<Char>^chars = {' ',',','->',':'};
array<String^>^split = words->Split( chars );
IEnumerator^ myEnum = split->GetEnumerator();
while ( myEnum->MoveNext() )
{
String^ s = safe_cast<String^>(myEnum->Current);
if ( !s->Trim()->Equals( "" ) )
Console::WriteLine( s );
}
}
I think you can do what you need to do with the String.Split method.
First, I think you're expecting the 'count' parameter to work differently: You're passing in 2, and expecting the first and second results to be returned, and the third result to be thrown out. What it actually return is the first result, and the second & third results concatenated into one string. If all you want is ThisISSomeTxt and PartNumberTwo, you'll want to manually throw away results after the first 2.
As far as I can tell, you don't want any whitespace included in your return strings. If that's the case, I think this is what you want:
String^ line = "ThisISSomeTxt \tPartNumberTwo PartNumber3";
array<String^>^ split = line->Split((array<String^>^)nullptr, StringSplitOptions::RemoveEmptyEntries);
for(int i = 0; i < split->Length && i < 2; i++)
{
Debug::WriteLine("{0}: '{1}'", i, split[i]);
}
Results:
0: 'ThisISSomeTxt'
1: 'PartNumberTwo'

Is there a .NET function to remove the first (and only the first) occurrence at the start of a string?

I was using the TrimStart function to do the following:
var example = "Savings:Save 20% on this stuff";
example = example.TrimStart("Savings:".ToCharArray());
I was expecting this to result in example having a value of "Save 20% on this stuff".
However, what I got was "e 20% on this stuff".
After reading the documentation on TrimStart I understand why, but now I'm left wondering if there is a function in .NET that does what I was trying to do in the first place?
Does anyone know of a function so I don't have to create my own and keep track of it?
I don't think such a method exists but you can easily do it using StartsWith and Substring:
s = s.StartsWith(toRemove) ? s.Substring(toRemove.Length) : s;
You can even add it as an extension method:
public static class StringExtension
{
public static string RemoveFromStart(this string s, string toRemove)
{
if (s == null)
{
throw new ArgumentNullException("s");
}
if (toRemove == null)
{
throw new ArgumentNullException("toRemove");
}
if (!s.StartsWith(toRemove))
{
return s;
}
return s.Substring(toRemove.Length);
}
}
No, I don't believe there's anything which does this built into the framework. It's a somewhat unusual requirement, IMO.
Note that you should think carefully about whether you're trying to remove "the first occurrence" or remove the occurrence at the start of the string, if there is one. For example, think what you'd want to do with: "Hello. Savings: Save 20% on this stuff".
You can do that quite easily using a regular expression.
Remove the occurrence on the beginning of the string:
example = Regex.Replace(example, #"^Savings:", "");
Remove the first occurrence in the string:
example = Regex.Replace(example, #"(?<!Savings:.*)Savings:", "");

Resources