How to remove word "null" from string in ActionScripts3 - actionscript-3

I have code for convert each 2 numbers to a specific character, this code works, but output is with an unwanted word "null". I want to remove it. I can't identify which part of code is wrong.
var encoded_numbers:String = "102030";
var sub:String;
var decode_string:String;
for (var i2:int = 0; i2 < encoded_numbers.length; i2 += 2)
{
sub = encoded_numbers.charAt(i2) + encoded_numbers.charAt(i2 + 1);
//trace(sub);
switch(sub)
{
case "10":
decode_string += "A";
break;
case "20":
decode_string += "B";
break;
case "30":
decode_string += "C";
break;
}
}
trace(decode_string);//convert
Output string:
nullABC

Initial value of your decode_string is null. Just assign the initial value as follows:
var decodeString:String = "";

"...but output is with an unwanted word "null". I want to remove it. I can't identify which part of code is wrong."
When you say : var decode_string:String; you've declared a variable but it has no value so by default it gives result of "null". The problem later is when you use += operator to further append your ABC letters, the final string has now become nullABC.
To fix :
Make your strings empty/blank (but never value-less) by using String = "";...
var encoded_numbers:String = "102030";
var sub:String = "";
var decode_string:String = "";
Also consider substr for extracting parts of texts (instead of charAt)..
for (var i2:int = 0; i2 < encoded_numbers.length; i2 += 2)
{
sub = encoded_numbers.substr(i2, 2); //gets 2 letters from position of i2
//trace(sub);
switch(sub)
{
case "10":
decode_string += "A";
break;
case "20":
decode_string += "B";
break;
case "30":
decode_string += "C";
break;
}
}
trace(decode_string);//convert

Related

How to merge arrays by index AS3

Seeking a way to merge arrays by index like so:
var a1:Array = ["a", "b", "c"];
var a2:Array = ["1", "2", "3"];
var a3:Array = result: ["a", 1, "b", 2, "c", 3]
I've tried concat, push, splice... not getting close. Thanks.
function arrayMerge(arr1:Array, arr2:Array):Array {
var o:Array = new Array();
for (var i:int=0; i<Math.max(arr1.length, arr2.length); i++) {
if (i<arr1.length) o.push(arr1[i]);
if (i<arr2.length) o.push(arr2[i]);
}
return o;
}
Thanks Payam for answer and non-judgement. Here's how I applied your work:
var arr1:Array = ["question1", "question2", "question3"];
var arr2:Array = ["answer1", "answer2", "answer3"];
var o:Array = new Array();
for (var i:int=0; i<Math.max(arr1.length, arr2.length); i++) {
if (i<arr1.length) o.push(arr1[i]);
if (i<arr2.length) o.push(arr2[i]);
}
trace(o); //(question1,answer1,question2,answer2,question3,question3)
#AndyH :
payamsbr is right, but you may work with Vectors or Arrays
Perhaps tl; dr; but this is the principle.
If You want to understand something try those possibilities.
If you don't, just copy and paste some shorter code ;)
var v1:Vector.<String> = new <String>["a", "b", "c"];
var v2:Vector.<uint> = new <uint>[1, 2, 3]; // why do you use String here and not uint?
// if you want to convert a uint to a String, use myUint.toString();
function convertVectorToArray(v1:Vector.<String>,v2:Vector.<uint>):Array{
var mergedArray:Array = new Array();
if (v1.length != v2.length){
throw(new Error(" ***ERROR : the two Vectors or Arrays have not the same lenfgth!"));
}else{
for(var i:uint = 0; i <v1.length ; i++){
mergedArray.push(v1[i]);
mergedArray.push(v2[i]);
}
}
return(mergedArray);
}
function mergeVectors(v1:Vector.<String>,v2:Vector.<uint>):Vector.<Object>{
var mergedVector:Vector.<Object> = new Vector.<Object>();
if (v1.length != v2.length){
throw(new Error(" ***ERROR : the two Vectors or Arrays have not the same length!"));
}
for(var i:uint = 0; i <v1.length ; i++){
mergedVector.push(v1[i] as String);
mergedVector.push(v2[i] as uint);
}
return(mergedVector);
}
var mergedArray:Array = (convertVectorToArray(v1,v2));
var mergedVector:Vector.<Object> = (mergeVectors(v1,v2));
function listArray(arr:Array):String{
var str: String="";
if ((v1.length*2) != (v1.length + v2.length)){
throw(new Error(" ***ERROR : the two Vectors or Arrays have not the same length!"));
}else{
for (var i:uint = 0; i < arr.length ; i++){
str+="typeof(arr[" + i + "]) = " + (typeof(arr[i]) as String).toUpperCase() + ", value = " + arr[i] + "\n";
}
}
return str;
}
function listVector(vect:Vector.<Object>):String{
var str: String = "";
if ((v1.length*2) != (v1.length + v2.length)){
throw(new Error(" ***ERROR : the two Vectors or Arrays have not the same length!"));
}else{
for (var i:uint = 0; i < vect.length ; i++){
str+="typeof(vect[" + i + "]) = " + (typeof(vect[i]) as String).toUpperCase() + ", value = " + vect[i] + "\n";
}
}
return str;
}
trace(listArray(mergedArray));
trace(listVector(mergedVector));
You may add a sort() method if You need it (you didn't told about it)
And Always throw an Error if the 2 Arrays or Vectors don't have the same length!
Throwing an Error is the best way to understand if something goes wrong...
This will avoid You a lot of time if You need to debug Your code!!!
As You can see the output is the same, but if the Vector Class is used correctly, this is more efficient than an Array.
Output :
Since there's a Vector Class, I don't understand a lot of people who chose Arrays instead...
Of course Vector. is a nonsense, but I posted it anyway so You can figure You out the Vector Class.
Output is the same :
typeof(arr[0]) = STRING, value = a
typeof(arr[1]) = NUMBER, value = 1
typeof(arr[2]) = STRING, value = b
typeof(arr[3]) = NUMBER, value = 2
typeof(arr[4]) = STRING, value = c
typeof(arr[5]) = NUMBER, value = 3
typeof(vect[0]) = STRING, value = a
typeof(vect[1]) = NUMBER, value = 1
typeof(vect[2]) = STRING, value = b
typeof(vect[3]) = NUMBER, value = 2
typeof(vect[4]) = STRING, value = c
typeof(vect[5]) = NUMBER, value = 3
I forgot this easiest way if you really want an Array...
Quick done!
var ar1:Array = [1,2,3];
var ar2:Array = ["a","b","c"];
function merge(...arrays):Array {
var result:Array = [];
for(var i:int=0;i<arrays.length;i++){
result = result.concat(arrays[i]);
}
return result;
}
trace(merge(ar1, ar2));
// outputs : 1,2,3,a,b,c
Another possibility :
function populateObject(v1:Vector.<String>, v2:Vector.<uint>):Object{
var obj = new Object();
if ((v1.length*2) != (v1.length + v2.length)){
throw(new Error(" ***ERROR : the two Vectors or Arrays have not the same length!"));
}else{
for (var i:uint = 0; i < v1.length; i++){
obj[v2[i]] = v1[i];
}
}
return obj;
}
var o:Object = populateObject(v1,v2);
function listObject(someObj:Object):void{
var myObj:Object = someObj;
for (var i:String in someObj){
trace(someObj[i] + ": " + i);
}
}
listObject(o);
output =
a: 1
b: 2
c: 3
I think that You have a lot of possibilities to use here even it's my longer answer ;)
If You try those possibilities and understand them, this will certainty help You to think to find the best way to deal with Your issue.
But You may also copy and paste some shorter code.
I just wanted to show You that there's more than one answer.
If you understand this, You will be able to go further with coding.
Have fun ;)
Sincerely.
Nicolas
Best regards.
Nicolas.

Overflow text when i'm Fill text in canvas [duplicate]

I am trying to add text on an image using the <canvas> element. First the image is drawn and on the image the text is drawn. So far so good.
But where I am facing a problem is that if the text is too long, it gets cut off in the start and end by the canvas. I don't plan to resize the canvas, but I was wondering how to wrap the long text into multiple lines so that all of it gets displayed. Can anyone point me at the right direction?
Updated version of #mizar's answer, with one severe and one minor bug fixed.
function getLines(ctx, text, maxWidth) {
var words = text.split(" ");
var lines = [];
var currentLine = words[0];
for (var i = 1; i < words.length; i++) {
var word = words[i];
var width = ctx.measureText(currentLine + " " + word).width;
if (width < maxWidth) {
currentLine += " " + word;
} else {
lines.push(currentLine);
currentLine = word;
}
}
lines.push(currentLine);
return lines;
}
We've been using this code for some time, but today we were trying to figure out why some text wasn't drawing, and we found a bug!
It turns out that if you give a single word (without any spaces) to the getLines() function, it will return an empty array, rather than an array with a single line.
While we were investigating that, we found another (much more subtle) bug, where lines can end up slightly longer than they should be, since the original code didn't account for spaces when measuring the length of a line.
Our updated version, which works for everything we've thrown at it, is above. Let me know if you find any bugs!
A possible method (not completely tested, but as for now it worked perfectly)
/**
* Divide an entire phrase in an array of phrases, all with the max pixel length given.
* The words are initially separated by the space char.
* #param phrase
* #param length
* #return
*/
function getLines(ctx,phrase,maxPxLength,textStyle) {
var wa=phrase.split(" "),
phraseArray=[],
lastPhrase=wa[0],
measure=0,
splitChar=" ";
if (wa.length <= 1) {
return wa
}
ctx.font = textStyle;
for (var i=1;i<wa.length;i++) {
var w=wa[i];
measure=ctx.measureText(lastPhrase+splitChar+w).width;
if (measure<maxPxLength) {
lastPhrase+=(splitChar+w);
} else {
phraseArray.push(lastPhrase);
lastPhrase=w;
}
if (i===wa.length-1) {
phraseArray.push(lastPhrase);
break;
}
}
return phraseArray;
}
Here was my spin on it... I read #mizar's answer and made some alterations to it... and with a little assistance I Was able to get this.
code removed, see fiddle.
Here is example usage. http://jsfiddle.net/9PvMU/1/ - this script can also be seen here and ended up being what I used in the end... this function assumes ctx is available in the parent scope... if not you can always pass it in.
edit
the post was old and had my version of the function that I was still tinkering with. This version seems to have met my needs thus far and I hope it can help anyone else.
edit
It was brought to my attention there was a small bug in this code. It took me some time to get around to fixing it but here it is updated. I have tested it myself and it seems to work as expected now.
function fragmentText(text, maxWidth) {
var words = text.split(' '),
lines = [],
line = "";
if (ctx.measureText(text).width < maxWidth) {
return [text];
}
while (words.length > 0) {
var split = false;
while (ctx.measureText(words[0]).width >= maxWidth) {
var tmp = words[0];
words[0] = tmp.slice(0, -1);
if (!split) {
split = true;
words.splice(1, 0, tmp.slice(-1));
} else {
words[1] = tmp.slice(-1) + words[1];
}
}
if (ctx.measureText(line + words[0]).width < maxWidth) {
line += words.shift() + " ";
} else {
lines.push(line);
line = "";
}
if (words.length === 0) {
lines.push(line);
}
}
return lines;
}
context.measureText(text).width is what you're looking for...
Try this script to wrap the text on a canvas.
<script>
function wrapText(ctx, text, x, y, maxWidth, lineHeight) {
var words = text.split(' ');
var line = '';
for(var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = ctx.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
ctx.fillText(line, x, y);
line = words[n] + ' ';
y += lineHeight;
}
else {
line = testLine;
}
}
ctx.fillText(line, x, y);
}
var canvas = document.getElementById('Canvas01');
var ctx = canvas.getContext('2d');
var maxWidth = 400;
var lineHeight = 24;
var x = (canvas.width - maxWidth) / 2;
var y = 70;
var text = 'HTML is the language for describing the structure of Web pages. HTML stands for HyperText Markup Language. Web pages consist of markup tags and plain text. HTML is written in the form of HTML elements consisting of tags enclosed in angle brackets (like <html>). HTML tags most commonly come in pairs like <h1> and </h1>, although some tags represent empty elements and so are unpaired, for example <img>..';
ctx.font = '15pt Calibri';
ctx.fillStyle = '#555555';
wrapText(ctx, text, x, y, maxWidth, lineHeight);
</script>
</body>
See demo here http://codetutorial.com/examples-canvas/canvas-examples-text-wrap.
From the script here: http://www.html5canvastutorials.com/tutorials/html5-canvas-wrap-text-tutorial/
I've extended to include paragraph support. Use \n for new line.
function wrapText(context, text, x, y, line_width, line_height)
{
var line = '';
var paragraphs = text.split('\n');
for (var i = 0; i < paragraphs.length; i++)
{
var words = paragraphs[i].split(' ');
for (var n = 0; n < words.length; n++)
{
var testLine = line + words[n] + ' ';
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > line_width && n > 0)
{
context.fillText(line, x, y);
line = words[n] + ' ';
y += line_height;
}
else
{
line = testLine;
}
}
context.fillText(line, x, y);
y += line_height;
line = '';
}
}
Text can be formatted like so:
var text =
[
"Paragraph 1.",
"\n\n",
"Paragraph 2."
].join("");
Use:
wrapText(context, text, x, y, line_width, line_height);
in place of
context.fillText(text, x, y);
I am posting my own version used here since answers here weren't sufficient for me. The first word needed to be measured in my case, to be able to deny too long words from small canvas areas. And I needed support for 'break+space, 'space+break' or double-break/paragraph-break combos.
wrapLines: function(ctx, text, maxWidth) {
var lines = [],
words = text.replace(/\n\n/g,' ` ').replace(/(\n\s|\s\n)/g,'\r')
.replace(/\s\s/g,' ').replace('`',' ').replace(/(\r|\n)/g,' '+' ').split(' '),
space = ctx.measureText(' ').width,
width = 0,
line = '',
word = '',
len = words.length,
w = 0,
i;
for (i = 0; i < len; i++) {
word = words[i];
w = word ? ctx.measureText(word).width : 0;
if (w) {
width = width + space + w;
}
if (w > maxWidth) {
return [];
} else if (w && width < maxWidth) {
line += (i ? ' ' : '') + word;
} else {
!i || lines.push(line !== '' ? line.trim() : '');
line = word;
width = w;
}
}
if (len !== i || line !== '') {
lines.push(line);
}
return lines;
}
It supports any variants of lines breaks, or paragraph breaks, removes double spaces, as well as leading or trailing paragraph breaks. It returns either an empty array if the text doesn't fit. Or an array of lines ready to draw.
look at https://developer.mozilla.org/en/Drawing_text_using_a_canvas#measureText%28%29
If you can see the selected text, and see its wider than your canvas, you can remove words, until the text is short enough. With the removed words, you can start at the second line and do the same.
Of course, this will not be very efficient, so you can improve it by not removing one word, but multiple words if you see the text is much wider than the canvas width.
I did not research, but maybe their are even javascript libraries that do this for you
I modified it using the code from here http://miteshmaheta.blogspot.sg/2012/07/html5-wrap-text-in-canvas.html
http://jsfiddle.net/wizztjh/kDy2U/41/
This should bring the lines correctly from the textbox:-
function fragmentText(text, maxWidth) {
var lines = text.split("\n");
var fittingLines = [];
for (var i = 0; i < lines.length; i++) {
if (canvasContext.measureText(lines[i]).width <= maxWidth) {
fittingLines.push(lines[i]);
}
else {
var tmp = lines[i];
while (canvasContext.measureText(tmp).width > maxWidth) {
tmp = tmp.slice(0, tmp.length - 1);
}
if (tmp.length >= 1) {
var regex = new RegExp(".{1," + tmp.length + "}", "g");
var thisLineSplitted = lines[i].match(regex);
for (var j = 0; j < thisLineSplitted.length; j++) {
fittingLines.push(thisLineSplitted[j]);
}
}
}
}
return fittingLines;
And then get draw the fetched lines on the canvas :-
var lines = fragmentText(textBoxText, (rect.w - 10)); //rect.w = canvas width, rect.h = canvas height
for (var showLines = 0; showLines < lines.length; showLines++) { // do not show lines that go beyond the height
if ((showLines * resultFont.height) >= (rect.h - 10)) { // of the canvas
break;
}
}
for (var i = 1; i <= showLines; i++) {
canvasContext.fillText(lines[i-1], rect.clientX +5 , rect.clientY + 10 + (i * (resultFont.height))); // resultfont = get the font height using some sort of calculation
}
This is a typescript version of #JBelfort's answer.
(By the way, thanks for this brilliant code)
As he mentioned in his answer this code can simulate html element such as textarea,and also the CSS property
word-break: break-all
I added canvas location parameters (x, y and lineHeight)
function wrapText(
ctx: CanvasRenderingContext2D,
text: string,
maxWidth: number,
x: number,
y: number,
lineHeight: number
) {
const xOffset = x;
let yOffset = y;
const lines = text.split('\n');
const fittingLines: [string, number, number][] = [];
for (let i = 0; i < lines.length; i++) {
if (ctx.measureText(lines[i]).width <= maxWidth) {
fittingLines.push([lines[i], xOffset, yOffset]);
yOffset += lineHeight;
} else {
let tmp = lines[i];
while (ctx.measureText(tmp).width > maxWidth) {
tmp = tmp.slice(0, tmp.length - 1);
}
if (tmp.length >= 1) {
const regex = new RegExp(`.{1,${tmp.length}}`, 'g');
const thisLineSplitted = lines[i].match(regex);
for (let j = 0; j < thisLineSplitted!.length; j++) {
fittingLines.push([thisLineSplitted![j], xOffset, yOffset]);
yOffset += lineHeight;
}
}
}
}
return fittingLines;
}
and you can just use this like
const wrappedText = wrapText(ctx, dialog, 200, 100, 200, 50);
wrappedText.forEach(function (text) {
ctx.fillText(...text);
});
}

How do I compare a string in Flash to the name of a variable?

I'm not entirely sure if this is possible at all, but I'm trying to take a string in Flash and check to see if it is the same as the name of an already existing variable. Here is a piece of my code:
var randomNumber:int;
var randomNumberS:String;
var Mem1:String;
var Mem2:String;
randomNumber = Math.floor(Math.random()*3);
randomnumberS = ("Mem" + String(randomNumber));
TGiven.text = [the randomnumberS string, except as either the variable name Mem1 or Mem2]
Is this a possible task, and if not, is there a better way to perform this task? It would be very useful as I plan on making many more variables that start with Mem with higher and higher numbers.
It would be optimal if the variables were a member of a class or Object, to which you could evaluate whether they exist using hasOwnProperty().
For example:
var obj:Object = {
Mem1: "value1",
Mem2: "value2"
};
You could test whether obj has a property by name:
obj.hasOwnProperty("Mem1");
Applying your example using random numbers:
for (var i = 0; i < 100; i++) {
var randomNumber:int = Math.floor(Math.random() * 3);
if (obj.hasOwnProperty("Mem" + randomNumber))
trace("Mem" + randomNumber + " exists.");
else
trace("Mem" + randomNumber + " does not exist.");
}
You can also use the in keyword, such as:
"Mem1" in obj;
Using the same example:
for (var i = 0; i < 100; i++) {
var randomNumber:int = Math.floor(Math.random() * 3);
if (("Mem" + randomNumber) in obj)
trace("Mem" + randomNumber + " exists.");
else
trace("Mem" + randomNumber + " does not exist.");
}

AS 3 know if only certain characters are inside a string

with AS3 is there a simple way to understand if a string is composed only with 2 characters? for instance binary number. Can I understand if the string that I am inspecting is composed only of 0 and 1?
Something like the following should do the trick :
private function isBinary(str:String):Boolean
{
var binary:Boolean = true;
for (var i:int = 0; i < str.length; i++)
{
if (str.charAt(i) != "0" && str.charAt(i) != "1")
{
binary = false;
break;
}
}
return binary;
}

Read set of numbers from txt file

I've been working on a project for a while but got stuck where I have a text file that contains a set of numbers in this format:
1-2-3-4
1-2-3-4
1-2-3-4
1-2-3-4
So I must read the numbers from the file and put them in an array according to the column so at the end I have
column1:Array (1,1,1,1)
column2:Array (2,2,2,2)
..... and so on. I can't figure how to do this.
What I managed to do was read all the file and have all the numbers in 1 array but just that.
Here's the code
var myTextLoader:URLLoader = new URLLoader;
var txtArray:Array;
myTextLoader.load(new URLRequest(inputFile.text));
myTextLoader.addEventListener(Event.COMPLETE,onLoaded);
function onLoaded(e:Event):void
{
txtArray = e.target.data.split(/\-|\n/g);
}
before split \n \r to array (reading with a loop)
and the same with... -
a loop in loop to get a multidimensional array
in mind the result is a "table"
finally to get a result do this.
variable[file][column]
a[2][3] ----> 4
;)
Try splitting it into two parts, first by line, then by element:
function onLoaded(e:Event):void
{
preArray:Array = e.target.data.split(/\n/g);
txtArray = new Array();
for(var i:int = 0; i < preArray.length; i++) {
txtArray.push(preArray[i].split(/\-/g));
}
}
This will give you a 2D array, which you'd access like this:
textArray[0][0]; // result: 1
textArray[2][3];
Et cetera.
Thanks to Llanis who gave me the idea. This is my final code. Sorry i didn't tag the language it never ocurred to me i'm new.
myTextLoader.load(new URLRequest(inputWX.text));
myTextLoader.addEventListener(Event.COMPLETE,onLoaded);
function onLoaded(e:Event):void
{
txtArray = e.target.data.split(/\-|\n/g);
var wArray:Array = new Array(txtArray.length/4);
var xArray:Array = new Array(txtArray.length/4);
var yArray:Array = new Array(txtArray.length/4);
var zArray:Array = new Array(txtArray.length/4);
var a:int = 0;
var b:int = 0;
var c:int = 0;
var d:int = 0;
var columna:int = 1;
for(var arrayIndex:int = 0; arrayIndex <= txtArray.length-1;arrayIndex++)
{
switch(columna){
case 1: wArray[a] = txtArray[arrayIndex]; a+=1;
break;
case 2: xArray[b] = txtArray[arrayIndex]; b+=1;
break;
case 3: yArray[c] = txtArray[arrayIndex]; c+=1;
break;
case 4: zArray[d] = txtArray[arrayIndex]; d+=1;
break;
}
if(columna == 4)
columna = 1;
else columna++;
}
}