Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2004-04-03
17
Medium Priority
?
341 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
  • +6
17 Comments
 
LVL 53

Expert Comment

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

Cd&
0
 
LVL 25

Expert Comment

by:Marcus Bointon
ID: 10751397
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
ID: 10751666
<?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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 25

Expert Comment

by:Marcus Bointon
ID: 10751793
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
ID: 10753042
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
ID: 10754756
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
ID: 10756080
sorry I forgot to mention this is asp. I should have posted in asp area
0
 
LVL 1

Author Comment

by:indyng
ID: 10756091
Squinky,

You are right, I should re-prase my question at a higher level
0
 
LVL 8

Expert Comment

by:fozylet
ID: 10757665
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
ID: 10760195
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
ID: 10760217
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
ID: 10763030
@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:Marcus Bointon
ID: 10763722
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
ID: 10763957
@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:Marcus Bointon
ID: 10764114
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
ID: 10846410
Closed, 500 points Not refunded.
CetusMOD
Community Support Moderator
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article covers the basics of the Sass, which is a CSS extension language. You will learn about variables, mixins, and nesting.
Shoutout to Emily Plummer (http://www.experts-exchange.com/members/eplummer26.html) for giving me this article! She did most of it, I just finished it up and posted it for her :)    Introduction In a previous article (http://www.experts-exchang…
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

722 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