Solved

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

Posted on 2004-04-03
17
331 Views
Last Modified: 2011-04-14
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



0
Comment
Question by:indyng
  • 4
  • 3
  • 2
  • +6
17 Comments
 
LVL 53

Expert Comment

by:COBOLdinosaur
Comment Utility
What language?  Table?  DB table? HTML table?  Read the string in from where?

Cd&
0
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
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
 
LVL 5

Expert Comment

by:MMeijer
Comment Utility
<?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
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
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
 
LVL 15

Expert Comment

by:VincentPuglia
Comment Utility
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
 
LVL 2

Expert Comment

by:poopall
Comment Utility
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
 
LVL 1

Author Comment

by:indyng
Comment Utility
sorry I forgot to mention this is asp. I should have posted in asp area
0
 
LVL 1

Author Comment

by:indyng
Comment Utility
Squinky,

You are right, I should re-prase my question at a higher level
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 8

Expert Comment

by:fozylet
Comment Utility
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
 
LVL 7

Expert Comment

by:ramesh12
Comment Utility
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
 
LVL 7

Expert Comment

by:ramesh12
Comment Utility
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
 
LVL 8

Expert Comment

by:fozylet
Comment Utility
@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
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
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
 
LVL 8

Expert Comment

by:fozylet
Comment Utility
@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
 
LVL 25

Expert Comment

by:Squinky
Comment Utility
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
 

Accepted Solution

by:
CetusMOD earned 0 total points
Comment Utility
Closed, 500 points Not refunded.
CetusMOD
Community Support Moderator
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

Most of the sites are being standardized with W3C Web Standards. W3C provides lot of web standard services to the web. They have the web specification, process and documentation for all the web standards. You can apply HTML, CSS and Accessibility st…
JavaScript has plenty of pieces of code people often just copy/paste from somewhere but never quite fully understand. Self-Executing functions are just one good example that I'll try to demystify here.
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now