How to split a string without specifying any separator in asp.net with C#? - string

I have a string with 1000 length. I need to split it and assign it to different controls. I do not have any character separator.
Since each string that I am assigning to controls do not contain same length. As of now I am doing it using substring in which i am specifying the length. But its becoming hectic for me as the length is huge.
Please suggest me is there any way to split and assign in simpler way?

You can use this string constructor:
var input = "Some 1000 character long string ...";
var inputChars = input.ToCharArray();
control1.Value = new string(inputChars, 0, 100); // chars 0-100 of input
control2.Value = new string(inputChars, 100, 20); // chars 100-120 of input
control3.Value = new string(inputChars, 120, 50); // chars 120-170 of input
...
Or using Substring:
var input = "Some 1000 character long string ...";
control1.Value = input.Substring(0, 100); // chars 0-100 of input
control2.Value = input.Substring(100, 20); // chars 100-120 of input
control3.Value = input.Substring(120, 50); // chars 120-170 of input
You could also do this
var parts = new []
{
Tuple.Create(0, 100),
Tuple.Create(100, 20),
Tuple.Create(120, 50),
}
var inputParts = parts.Select(p => input.Substring(p.Item1, p.Item2))
.ToArray();
control1.Value = inputParts[0];
control2.Value = inputParts[1];
control3.Value = inputParts[3];
This makes it much easier to maintain as the number of controls grows larger. You can store this list of 'parts' statically, so it can be reused elsewhere in your application without duplicating the code.
If all the controls the same type, you can do this:
var parts = new []
{
new { control = control1, offset = 0, length = 100 },
new { control = control2, offset = 100, length = 20 },
new { control = control3, offset = 120, length = 50 },
}
foreach(var part in parts)
{
part.control.Value = new string(inputChars, part.offset, offset.length);
// or part.control.Value = input.Substring(part.offset, offset.length);
}

You won't get around specifying the information which control gets which part of the string. Once you have this information (let's say they are stored in a control array controls and int array length), you can just loop over the string and do a piecewise Substring:
var controls = { control1, control2, control3, ... };
var lengths = { 100, 20, 5, ... };
int offset = 0;
for (int i = 0; i < controls.length; i++) {
controls[i].Value = myLongString.Substring(offset, lengths[i]);
offset += lengths[i];
}
Obviously, this will fail horribly if myLongString is shorter than the sum of all lengths or the array length of lengths is shorter than the one of controls, but adding some checks for that and throwing a suitable error is left as an exercise to the reader. In addition, the controls must be compatible in the sense that they all derive from the same base class with a common Value property. If that is not the case, you might have to do a few type checks and casts inside the loop.

Related

How to set maximum length in String value DART

i am trying to set maximum length in string value and put '..' instead of removed chrs like following
String myValue = 'Welcome'
now i need the maximum length is 4 so output like following
'welc..'
how can i handle this ? thanks
The short and incorrect version is:
String abbrevBad(String input, int maxlength) {
if (input.length <= maxLength) return input;
return input.substring(0, maxLength - 2) + "..";
}
(Using .. is not the typographical way to mark an elision. That takes ..., the "ellipsis" symbol.)
A more internationally aware version would count grapheme clusters instead of code units, so it handles complex characters and emojis as a single character, and doesn't break in the middle of one. Might also use the proper ellipsis character.
String abbreviate(String input, int maxLength) {
var it = input.characters.iterator;
for (var i = 0; i <= maxLength; i++) {
if (!it.expandNext()) return input;
}
it.dropLast(2);
return "${it.current}\u2026";
}
That also works for characters which are not single code units:
void main() {
print(abbreviate("argelbargle", 7)); // argelb…
print(abbreviate("πŸ‡©πŸ‡°πŸ‡©πŸ‡°πŸ‡©πŸ‡°πŸ‡©πŸ‡°πŸ‡©πŸ‡°", 4)); // πŸ‡©πŸ‡°πŸ‡©πŸ‡°πŸ‡©πŸ‡°β€¦
}
(If you want to use ... instead of …, just change .dropLast(2) to .dropLast(4) and "…" to "...".)
You need to use RichText and you need to specify the overflow type, just like this:
Flexible(
child: RichText("Very, very, very looong text",
overflow: TextOverflow.ellipsis,
),
);
If the Text widget overflows, some points (...) will appears.

Insert commas into string number

I have this code, and I want to put commas.
I've seen many examples, but I dont now were put the code.
This is my AS3 code:
calccn.addEventListener(MouseEvent.CLICK,result1);
function result1(e:MouseEvent)
{
var vev: Number = (Number(vev.text));
var cn1: Number = (Number(3/100));
var result1f: Number = (Number(vev*cn1));
var round;
round=result1f.toFixed(0);
v3.text = String(round);
}
Example
If the result give me 1528000,32
I want that the result is 1.528.000 or 1 528 000
I didn't know (live and learn, eh), but there's actually a dedicated class: NumberFormatter.
If you want to do the thing on a regular basis, you might want a method to call:
// Implementation.
import flash.globalization.NumberFormatter;
// The default separator is comma.
function formattedNumber(value:Number, separator:String = ","):String
{
var NF:NumberFormatter;
NF = new NumberFormatter("en_US");
// Enforce the use of the given separator.
NF.groupingSeparator = separator;
// Ignore the fraction part.
NF.fractionalDigits = 0;
return NF.formatNumber(value);
}
// Usage.
//Format the given number with spaces for separator.
trace(formattedNumber(1528000.32, " ")); // 1 528 000
//Format the given number with the default separator.
trace(formattedNumber(1528000.32)); // 1,528,000
But if you want just a simple one-timer, and don't really care if it is commas or spaces as long as they present you may just condense in into a single expression:
calccn.addEventListener(MouseEvent.CLICK, result1);
function result1(e:MouseEvent):void
{
// Declaring variables with the same names as
// other entities is a generally bad idea.
var input:Number = Number(vev.text);
var cn1:Number = 3.0 / 100.0;
// Keep in mind that I used int() here as
// a simple tool to remove the fraction part.
v3.text = (new NumberFormatter("en_US")).formatNumber(int(input * cn1));
}

How to convert string to binary representation in game maker?

I found a script that converts binary to string but how can I input a string and get the binary representation? so say I put in "P" I want it to output 01010000 as a string.
I have this but it is not what I am trying to do - it converts a string containing a binary number into a real value of that number:
///string_to_binary(string)
var str = argument0;
var output = "";
for(var i = 0; i < string_length(str); i++){
if(string_char_at(str, i + 1) == "0"){
output += "0";
}
else{
output += "1";
}
}
return real(output);
Tip: search for GML or other language term, these questions answered many times. Also please check your tag as it is the IDE tag, not language tag.
Im not familiar with GML myself, but a quick search showed this:
At least semi-official method for exactly this: http://www.gmlscripts.com/script/bytes_to_bin
/// bytes_to_bin(str)
//
// Returns a string of binary digits, 1 bit each.
//
// str raw bytes, 8 bits each, string
//
/// GMLscripts.com/license
{
var str, bin, p, byte;
str = argument0;
bin = "";
p = string_length(str);
repeat (p) {
byte = ord(string_char_at(str,p));
repeat (8) {
if (byte & 1) bin = "1" + bin else bin = "0" + bin;
byte = byte >> 1;
}
p -= 1;
}
return bin;
}
GML forum (has several examples) https://www.reddit.com/r/gamemaker/comments/4opzhu/how_could_i_convert_a_string_to_binary/
///string_to_binary(string)
var str = argument0;
var output = "";
for(var i = 0; i < string_length(str); i++){
if(string_char_at(str, i + 1) == "0"){
output += "0";
}
else{
output += "1";
}
}
return real(output);
And other language examples:
C++ Fastest way to Convert String to Binary?
#include <string>
#include <bitset>
#include <iostream>
using namespace std;
int main(){
string myString = "Hello World";
for (std::size_t i = 0; i < myString.size(); ++i)
{
cout << bitset<8>(myString.c_str()[i]) << endl;
}
}
Java: Convert A String (like testing123) To Binary In Java
String s = "foo";
byte[] bytes = s.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
System.out.println("'" + s + "' to binary: " + binary);
JS: How to convert text to binary code in JavaScript?
function convert() {
var output = document.getElementById("ti2");
var input = document.getElementById("ti1").value;
output.value = "";
for (var i = 0; i < input.length; i++) {
output.value += input[i].charCodeAt(0).toString(2) + " ";
}
}
I was looking around for a simple GML script to convert a decimal to binary and return the bits in an array. I didn't find anything for my need and to my liking so I rolled my own. Short and sweet.
The first param is the decimal number (string or decimal) and the second param is the bit length.
// dec_to_bin(num, len);
// argument0, decimal string
// argument1, integer
var num = real(argument0);
var len = argument1;
var bin = array_create(len, 0);
for (var i = len - 1; i >= 0; --i) {
bin[i] = floor(num % 2);
num -= num / 2;
}
return bin;
Usage:
dec_to_bin("48", 10);
Output:
{ { 0,0,0,0,1,1,0,0,0,0 }, }
i think the binary you mean is the one that computers use, if thats the case, just use the common binary and add a kind of identification.
binary is actually simple, instead of what most people think.
every digit represents the previous number *2 (2ΒΉ, 2Β², 2Β³...) so we get:
1, 2, 4, 8, 16, 32, 64, 128, 256, 512...
flip it and get:
...512, 256, 128, 64, 32, 16, 8, 4, 2, 1
every digit is "activated" with 1's, plus all the activated number ant thats the value.
ok, so binary is basically another number system, its not like codes or something. Then how are letters and other characters calculated?
they arent ;-;
we just represent then as their order on their alphabets, so:
a=1
b=2
c=3
...
this means that "b" in binary would be "10", but "2" is also "10". So thats where computer's binary enter.
they just add a identification before the actual number, so:
letter_10 = b
number_10 = 2
signal_10 = "
wait, but if thats binary there cant be letter on it, instead another 0's and 1's are used, so:
011_10 = b
0011_10 = 2
001_10 = "
computers also cant know where the number starts and ends, so you have to always use the same amount of numbers, which is 8. now we get:
011_00010 = b
0011_0010 = 2
001_00010 = "
then remove the "_" cuz again, computers will only use 0's and 1's. and done!
so what i mean is, just use the code you had and add 00110000 to the value, or if you want to translate these numbers to letters as i wanted just add 01100000
in that case where you have the letter and wants the binary, first convert the letter to its number, for it just knows that the letters dont start at 1, capitalized letters starts at 64 and the the non-capitalized at 96.
ord("p")=112
112-96=16
16 in binary is 10000
10000 + 01100000 = 01110000
"p" in binary is 01110000
ord("P")=80
80-64=16
16 in binary is 10000
10000 + 01000000 = 01010000
"P" in binary is 01010000
thats just a explanation of what the code should do, actually im looking for a simple way to turn binary cuz i cant understand much of the code you showed.
(011)
1000 1111 10000 101 1001 1000 101 1100 10000 101 100

AS3 "Advanced" string manipulation

I'm making an air dictionary and I have a(nother) problem. The main app is ready to go and works perfectly but when I tested it I noticed that it could be better. A bit of context: the language (ancient egyptian) I'm translating from does not use punctuation so a phrase canlooklikethis. Add to that the sheer complexity of the glyph system (6000+ glyphs).
Right know my app works like this :
user choose the glyphs composing his/r word.
app transforms those glyphs to alphanumerical values (A1 - D36 - X1A, etc).
the code compares the code (say : A5AD36) to a list of xml values.
if the word is found (A5AD36 = priestess of Bast), the user gets the translation. if not, s/he gets all the possible words corresponding to the two glyphs (A5A & D36).
If the user knows the string is a word, no problem. But if s/he enters a few words, s/he'll have a few more choices than hoped (exemple : query = A1A5AD36 gets A1 - A5A - D36 - A5AD36).
What I would like to do is this:
query = A1A5AD36 //word/phrase to be translated;
varArray = [A1, A5A, D36] //variables containing the value of the glyphs.
Corresponding possible words from the xml : A1, A5A, D36, A5AD36.
Possible phrases: A1 A5A D36 / A1 A5AD36 / A1A5A D36 / A1A5AD36.
Possible phrases with only legal words: A1 A5A D36 / A1 A5AD36.
I'm not I really clear but to things simple, I'd like to get all the possible phrases containing only legal words and filter out the other ones.
(example with english : TOBREAKFAST. Legal = to break fast / to breakfast. Illegal = tobreak fast.
I've managed to get all the possible words, but not the rest. Right now, when I run my app, I have an array containing A1 - A5A - D36 - A5AD36. But I'm stuck going forward.
Does anyone have an idea ? Thank you :)
function fnSearch(e: Event): void {
var val: int = sp.length; //sp is an array filled with variables containing the code for each used glyph.
for (var i: int = 0; i < val; i++) { //repeat for every glyph use.
var X: String = ""; //variable created to compare with xml dictionary
for (var i2: int = 0; i2 < val; i2++) { // if it's the first time, use the first glyph-code, else the one after last used.
if (X == "") {
X = sp[i];
} else {
X = X + sp[i2 + i];
}
xmlresult = myXML.mot.cd; //xmlresult = alphanumerical codes corresponding to words from XMLList already imported
trad = myXML.mot.td; //same with traductions.
for (var i3: int = 0; i3 < xmlresult.length(); i3++) { //check if element X is in dictionary
var codeElement: XML = xmlresult[i3]; //variable to compare with X
var tradElement: XML = trad[i3]; //variable corresponding to codeElement
if (X == codeElement.toString()) { //if codeElement[i3] is legal, add it to array of legal words.
checkArray.push(codeElement); //checkArray is an array filled with legal words.
}
}
}
}
var iT2: int = 500 //iT2 set to unreachable value for next lines.
for (var iT: int = 0; iT < checkArray.length; iT++) { //check if the word searched by user is in the results.
if (checkArray[iT] == query) {
iT2 = iT
}
}
if (iT2 != 500) { //if complete query is found, put it on top of the array so it appears on top of the results.
var oldFirst: String = checkArray[0];
checkArray[0] = checkArray[iT2];
checkArray[iT2] = oldFirst;
}
results.visible = true; //make result list visible
loadingResults.visible = false; //loading screen
fnPossibleResults(null); //update result list.
}
I end up with an array of variables containing the glyph-codes (sp) and another with all the possible legal words (checkArray). What I don't know how to do is mix those two to make legal phrases that way :
If there was only three glyphs, I could probably find a way, but user can enter 60 glyphs max.

Grabbing text from webpage and storing as variable

On the webpage
http://services.runescape.com/m=itemdb_rs/Armadyl_chaps/viewitem.ws?obj=19463
It lists prices for a particular item in a game, I wanted to grab the "Current guide price:" of said item, and store it as a variable so I could output it in a google spreadsheet. I only want the number, currently it is "643.8k", but I am not sure how to grab specific text like that.
Since the number is in "k" form, that means I can't graph it, It would have to be something like 643,800 to make it graphable. I have a formula for it, and my second question would be to know if it's possible to use a formula on the number pulled, then store that as the final output?
-EDIT-
This is what I have so far and it's not working not sure why.
function pullRuneScape() {
var page = UrlFetchApp.fetch("http://services.runescape.com/m=itemdb_rs/Armadyl_chaps/viewitem.ws?obj=19463").getContentText();
var number = page.match(/Current guide price:<\/th>\n(\d*)/)[1];
SpreadsheetApp.getActive().getSheetByName('RuneScape').appendRow([new Date(), number]);
}
Your regex is wrong. I tested this one successfully:
var number = page.match(/Current guide price:<\/th>\s*<td>([^<]*)<\/td>/m)[1];
What it does:
Current guide price:<\/th> find Current guide price: and closing td tag
\s*<td> allow whitespace between tags, find opening td tag
([^<]*) build a group and match everything except this char <
<\/td> match the closing td tag
/m match multiline
Use UrlFetch to get the page [1]. That'll return an HTTPResponse that you can read with GetBlob [2]. Once you have the text you can use regular expressions. In this case just search for 'Current guide price:' and then read the next row. As to remove the 'k' you can just replace with reg ex like this:
'123k'.replace(/k/g,'')
Will return just '123'.
https://developers.google.com/apps-script/reference/url-fetch/
https://developers.google.com/apps-script/reference/url-fetch/http-response
Obviously, you are not getting anything because the regexp is wrong. I'm no regexp expert but I was able to extract the number using basic string manipulation
var page = UrlFetchApp.fetch("http://services.runescape.com/m=itemdb_rs/Armadyl_chaps/viewitem.ws?obj=19463").getContentText();
var TD = "<td>";
var start = page.indexOf('Current guide price');
start = page.indexOf(TD, start);
var end = page.indexOf('</td>',start);
var number = page.substring (start + TD.length , end);
Logger.log(number);
Then, I wrote a function to convert k,m etc. to the corresponding multiplying factors.
function getMultiplyingFactor(symbol){
switch(symbol){
case 'k':
case 'K':
return 1000;
case 'm':
case 'M':
return 1000 * 1000;
case 'g':
case 'G':
return 1000 * 1000 * 1000;
default:
return 1;
}
}
Finally, tie the two together
function pullRuneScape() {
var page = UrlFetchApp.fetch("http://services.runescape.com/m=itemdb_rs/Armadyl_chaps/viewitem.ws?obj=19463").getContentText();
var TD = "<td>";
var start = page.indexOf('Current guide price');
start = page.indexOf(TD, start);
var end = page.indexOf('</td>',start);
var number = page.substring (start + TD.length , end);
Logger.log(number);
var numericPart = number.substring(0, number.length -1);
var multiplierSymbol = number.substring(number.length -1 , number.length);
var multiplier = getMultiplyingFactor(multiplierSymbol);
var fullNumber = multiplier == 1 ? number : numericPart * multiplier;
Logger.log(fullNumber);
}
Certainly, not the optimal way of doing things but it works.
Basically I parse the html page as you did (with corrected regex) and split the string into number part and multiplicator (k = 1000). Finally I return the extracted number. This function can be used in Google Docs.
function pullRuneScape() {
var pageContent = UrlFetchApp.fetch("http://services.runescape.com/m=itemdb_rs/Armadyl_chaps/viewitem.ws?obj=19463").getContentText();
var matched = pageContent.match(/Current guide price:<.th>\n<td>(\d+\.*\d*)([k]{0,1})/);
var numberAsString = matched[1];
var multiplier = "";
if (matched.length == 3) {
multiplier = matched[2];
}
number = convertNumber(numberAsString, multiplier);
return number;
}
function convertNumber(numberAsString, multiplier) {
var number = Number(numberAsString);
if (multiplier == 'k') {
number *= 1000;
}
return number;
}

Resources