How can I read a string of characters into an array?

Hi Experts,

I want to accomplish the following:

- read in a string of characters such as the following into an array

2 a13 3 s4 2 a7b

- go through the array and read each character one at a time

If the character is a number it will be stored into a variable called 'quantity' and next character being a text will be stored into variable called 'itemcode'. Then some code to insert data into a table will be accomplished. I already have this part. After the data insertion is completed, the next character is read. 3 is read and stored into 'quantity'. Next s4 is read from the array and stored into 'itemcode', the data insertion into a table is repeated again. This process will continue until all the characters are read from the array.

How can I accomplish the above?

Thanks



LVL 1
indyngAsked:
Who is Participating?
 
CetusMODConnect With a Mentor Commented:
Closed, 500 points Not refunded.
CetusMOD
Community Support Moderator
0
 
COBOLdinosaurCommented:
What language?  Table?  DB table? HTML table?  Read the string in from where?

Cd&
0
 
Marcus BointonCommented:
I think your phrasing of the question was a bit confusing! Given that you're trying to find out how to do something, you're better off describing your objectives at a higher level. I think it's better describing that your string contains pairs of values: a quantity followed by an item code, and there may be any number of these pairs. Reading it character by character is not really a good approach, and any scripting language will be able to do better than that.

Here's an example (working & tested) of how to handle it in PHP:

<?php
$inputstring = '2 a13 3 s4 2 a7b';
$matches = array();
$offset = 0;
do {
      if (preg_match('/(\d+)\s+(\w+)\s*/', $inputstring, $matches, 0, $offset)) {
            $quantity = (integer)$matches[1];
            $itemcode = $matches[2];
            $offset += strlen($matches[0]);
            handleitem($quantity, $itemcode);
      } else
            break;
} while (1);

function handleitem($quantity, $itemcode) {
      print "Order $quantity of itemcode $itemcode\n";
      //Obviously, put whatever else you need to do here, store in DB etc
}
?>

This example produces this output:
Order 2 of itemcode a13
Order 3 of itemcode s4
Order 2 of itemcode a7b

The important part of this script is the regular expression in the preg_match function. That says "match a sequence of characters that starts with one of more numbers, followed by one or more spaces, followed by a string of one or more letters or numbers followed by 0 or more spaces" (so it works at the end of the string too). The preg_match function returns the matched parts in an array where the 0 element contains the full matched pattern, and subsequent elements contain the subpatterns.

The offset value keeps track of where it has got to in the input string.

I couldn't tell you the exact syntax to do this in ASP (if you're not using PHP), but the regular expression would probably be identical and the structure would be the same.

You don't say where this input string comes from, so I'm assuming you have that part sorted out can put it into the equivalent of the inputstring variable here.

Note that this uses a feature introduced in PHP 4.3.3, so you'll need at least that version.
0
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

 
MMeijerCommented:
<?php

$strInput = "2 a13 3 s4 2 a7b";
$arrInput = explode(" ", $strInput);

for($i=0; $i<count($arrInput); $i++)
{
      if(!is_numeric($arrInput[$i]) && $i>0)
      {
            echo("itemcode={$arrInput[$i]}<br />quantity={$arrInput[$i - 1]}<br />");
      }
}

?>

<% @language="javascript" %>
<%

var strInput = "2 a13 3 s4 2 a7b";
var arrInput = strInput.split(" ");

for(var i=0;i<arrInput.length;i++)
{
      if(isNaN(arrInput[i]) && i>0)
      {
            Response.Write("itemcode=" + arrInput[i] + "<br />quantity=" + arrInput[i - 1] + "<br />");
      }
}

%>

<%

Dim strInput, arrInput, i

strInput = "2 a13 3 s4 2 a7b"
arrInput = split(strInput, " ")

For i=0 To ubound(arrInput)
      If not isNumeric(arrInput(i)) and i>0 then
            Response.Write "itemcode=" & arrInput(i) & "<br />quantity=" & arrInput(i - 1) & "<br />"
      End If
Next

%>
0
 
Marcus BointonCommented:
Those are very neat examples, but that kind of approach is extremely prone to error, for example if there is more than one space between entries. You have also made the implicit assumption that there is no such thing as an itemcode that's just a number. Searching for quantity/item pairs together and applying source validation (which is implicit in the use of the regex) is a far more robust approach. You should always code defensively.
0
 
VincentPugliaCommented:
Hi,
 
  With above caveats & cobolDinosaur's comment in mind,
here is a javascript solution:

<script type='text/javascript'>
var itemcode = new Array();
var quantity = new Array();
var myString = "2 a13 3 s4 2 a7b";
var tmpArray = myString.split(" ");
for (var i = 0, j = 0; i < tmpArray.length; i++)
   (i % 2 == 0) ? quantity[j] = tmpArray[i] :
     itemcode[j++] = tmpArray[i];


for (var i = 0; i < quantity.length; i++)
alert(quantity[i] + ' of ' + itemcode[i])
</script>

Vinny
0
 
poopallCommented:
If this is ASP then you can use the split command

MySplitArray = Split(2 a13 3 s4 2 a7b," ") which will spilt every time these is a blank space in the string
0
 
indyngAuthor Commented:
sorry I forgot to mention this is asp. I should have posted in asp area
0
 
indyngAuthor Commented:
Squinky,

You are right, I should re-prase my question at a higher level
0
 
fozyletCommented:
myArray = Split("2 a13 3 s4 2 a7b")
For iCnt=0 To UBound(myArray) Step 2
    myQty(iCnt/2)=myArray(iCnt)
    myItem(iCnt/2+1)=myArray(iCnt+1)
Next

Now the arrays myQty and myItem contain the corresponding item/quantity
0
 
ramesh12Commented:
A bit lazy. So I am copying fozylet's code

myArray = Split("2 a13 3 s4 2 a7b"," ")               --- ------ Change here
For iCnt=0 To UBound(myArray)
   
'myArray(iCnt) gives you each element in the array

Next

0
 
ramesh12Commented:
myArray = Split("2 a13 3 s4 2 a7b"," ")               --- ------ Change here
For iCnt=0 To UBound(myArray)  step 2
   
'myArray(iCnt) gives you each element in the array
quantity=myArray(iCnt)
itemcode=myArray(iCnt+1)


Next
0
 
fozyletCommented:
@ramesh12,
That is from microsoft. Please note that the default delimiter is space and need not be mentioned. So my code works without any change. FYI.

Split(expression[, delimiter[, count[, compare]]])

delimiter
Optional. String character used to identify substring limits. If omitted, the space character (" ") is assumed to be the delimiter. If delimiter is a zero-length string, a single-element array containing the entire expression string is returned.
0
 
Marcus BointonCommented:
Before anyone posts yet another example of doing this in ASP (no less than 4 duplicates since MMeijer's post), I'd like to reiterate my earlier comment about using split. Though it is the most obvious thing to use, it is clearly not the most reliable or error resistant, so I'd suggest you don't use it at all, or if you do, to apply further validation to the resulting items before using them. There is more than enough advice in here to answer indyng's original question, in any language!
0
 
fozyletCommented:
@Squinky,
What are the errors you expect in using Split? If the array is alternating between quantities and corresponding items with a space in between, i don't see a problem in using split. And note that there is significant difference between my code and MMeijer's. Please see the code and differences, if any, before making such comments (as duplicating)

Thanks
0
 
Marcus BointonCommented:
No harm meant. There's nothing wrong with split itself, but It's extremely common to receive bad data, and in general you should not assume that data you are being fed is always perfect, and be able to cope with variations, and split is not much use in that context as it's too inflexible an approach. Excess whitespace is probably the most common example. For example, what happens if there's an additional space, e.g. you receive: 2 a13 3 s4 2 a7b instead of 2  a13 3 s4 2 a7b? Your code would probably result in this disastrous output:
2
a13 3
s4 2
a7b <index out of range error>

If you now throw validation into the mix you can get even better reliability, for example in your code's output, you would easily be able to spot that the quantities were not numeric amounts.

You might think "but I'm never going to be receiving bad data"? Really? Try this: write a script that calls one of your own ASP scripts, supplying large amounts of random data into its usual parameters. Does it still work? Does it fill your database with rubbish? Don't think this will never happen - scripts that are on the public internet may have this happen at any time - around half the world's spam is sent through exposed server scripts without their owners knowing. Thinking it will not happen to you is just complacency on your part. There's no excuse for not coding defensively and validating carefully. Using regexes instead of split is a good start on that approach, as if the data is not precisely the right "shape", it will be rejected immediately and not progress any further. When you read about security holes being found in web sites, it's precisely simple things like this that are behind them.

If this was a purely academic question that did guarantee that the data was always perfect, then your code would be quite reasonable, however, this looks like it's for some kind of shopping-cart type application, and thus likely to be exposed to the net, in which case, it's not safe.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.