473,387 Members | 1,545 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Splitting a long string

Hi All,
I have a string of 1500 or more characters. but I want to go through this string and split it at the 160th but it should not split in the middle of the word. If the 160th character is not the end of a word it should go back to the next word and split from that. My code is below but its not working well

Expand|Select|Wrap|Line Numbers
  1. sub get_horoscope {
  2.     my($dbh,$thetype, $hname, $phone)=@_;
  3.     my($val,$sth,$rec,$horoscope,$subset,$i);
  4.     $sth=$dbh->prepare("SELECT ? FROM horoscope_table WHERE `horoscope_name`  = '$hname'");
  5.     my($more)=$dbh->prepare("INSERT INTO chat_outbox (`sender`, `phone`,`text`,`insertdate`) VALUES ('466',TRIM(?),TRIM(?),NOW())");
  6.     $sth->execute($thetype);
  7.     $horoscope="";
  8.     my(@types);
  9.     my($start, $end) = (0, 160);
  10.     my $set = length($rec->{'$thetype'}) % 160;
  11.     while($rec=$sth->fetchrow_hashref()) {
  12.     if(length($rec->{'$thetype'}) > 160){
  13.         for($i = 0; $i <= $set; $i++){
  14.             $subset = substr($rec->{'$thetype'}, $start, $end);
  15.             $start+=160;
  16.             $end+=160;
  17.             $more->execute($subset);
  18.             }else{
  19.                 $horoscope = "$horoscope\n$rec->{'$thetype'}";  
  20.             }    
  21.         }
  22.     }
  23.     $sth->finish();
  24.     syslog('info',__LINE__."::[get_horoscope] $horoscope");
  25.     return ($horoscope);
  26. }
Dec 4 '10 #1
11 5033
numberwhun
3,509 Expert Mod 2GB
Would you be able to provide a sample of the data with which you are working? That way we can have something to work with that you are also using.

Regards,

Jeff
Dec 4 '10 #2
toolic
70 Expert
Text::Wrap
Dec 5 '10 #3
Expand|Select|Wrap|Line Numbers
  1. $i=22;
  2. $String="A Computer is an Electronic Device";
  3. until(substr($String, $i, 1)eq " ") {
  4. $i++;
  5. }
  6. print substr($String, 0, $i);
  7.  
  8. # here the 22nd character is 't' or 'r' in Electronic Word... But it will print the whole "A Computer is an Electronic" as output... Just try...
  9.  
  10.  
Answers from
EMAIL REMOVED
Dec 7 '10 #4
Thanks for that I really appreciate your efforts..
Dec 7 '10 #5
chaarmann
785 Expert 512MB
You can do it with a regular expression.
I have developed following regular expression and used it successfully with Java (I haven't tried it yet, but it should also work with Perl). The regular expression got a bit complicated, because I wanted it to work for any line length (not only 160) and for any text (also for empty text or short text or text with words that are longer than a line etc.), so I commented it well. The spaces should be preserved in a way that concatenationg all parts should give back the old string exactly as it was. If possible, the split should be done after the space.

If the string contains newline-characters, split it first by newline-character and then apply the regular expression on each part.

With help of the regular expression I will insert a newline-character everywhere where the split should occur, so I avoid passing arrays around (and concatenating array parts when saving to database or searching inside etc. later on).

In the explanation below, "4" is an example value and should be replaced with the value of the constant MAX_LINE_LENGTH.
The following regular expression splits the string into parts with length of maximum 4 characters using following rules in following order
  1. don't split if the whole line (or remainder) is less than 4 characters. regEx="(?s).{1,4}$"
  2. if the word is bigger than 4 characters, split the word inside. regEx="[^\s]{4}"
  3. split before last space if a space follows exactly after 4 characters. regEx="(?s).{4}(?=\s)"
  4. split behind last space before maximum 4 character regEx="(?s).{0,3}\s"
Example: splitting "12345 67 8 9ab c de wxyz1 2 4 5 678" yields "1234", "5 67", " 8 ", "9ab ", "c de", " ", "wxyz", "1 2 ", "4 5 ", "678".

In Java:
Expand|Select|Wrap|Line Numbers
  1. int maxLineLength=4; // usually you will get this value from your configuration file
  2. String oldText="12345 67 8 9ab c de wxyz1 2 4 5 678"; // this is the String you want to split
  3.  
  4. // verify parameters.
  5. // The line should be splitted at newline-characters already before.
  6.  if (maxLineLength < 1) throw new Exception("ERROR: maxLineLength is " + maxLineLength + ", but must be greater than 0!");
  7. if (oldText == null) throw new Exception("ERROR: text must not be null!");
  8. if (oldText.indexOf("\n") != -1) throw new Exception("ERROR: text must not contain newline characters!");
  9.  
  10. // quick way out to increase performance
  11. if (oldText.isEmpty()) return "";
  12.  
  13. final String regularExpression = "(?s).{1," + maxLineLength + "}$|[^\\s]{" + maxLineLength + "}|(?s).{" + maxLineLength + "}(?=\\s)|(?s).{0," + (maxLineLength - 1) + "}\\s";
  14.  
  15. // insert newlines where we want to split the string into parts.
  16. // Note: Trailing empty strings are not included in the resulting array of the split() method. So the newline-char at the end of newText will have no effect. 
  17. String newText = oldText.replaceAll(regularExpression, "$0\n"); // append newline  
  18.  
  19. return newText; 
  20.  
Now you know the logic, so I leave it for you as an exercise to convert this program to Perl. Sorry, but I have no time any more to do it myself today. If you have difficulties, come back to me tomorrow and I will help you doing it.
Dec 7 '10 #6
chaarmann
785 Expert 512MB
deleted deleted
Dec 7 '10 #7
rovf
41
it should go back to the next word

Do you mean: "go back to the previous word" or "go forward to the next word"?
Dec 8 '10 #8
back to the previous word, because the subsentence should not be more than 160 characters..
Dec 8 '10 #9
rovf
41
Then, as toolic already suggested, Text::Wrap should do it.
Dec 8 '10 #10
chaarmann
785 Expert 512MB
Module Text:Wrap is exactly the same what my solution is doing, too. So if this module is not installed on production environment or you are not allowed to install it, you can use my solution instead. Also my solution can be easier modified in case you want its behaviour slightly changed.

Here it is in Perl:
Expand|Select|Wrap|Line Numbers
  1. #!/usr/local/perl-5.9-64/bin/perl
  2.  
  3. package test;
  4.  
  5. use warnings; 
  6. use strict;
  7.  
  8. # main program
  9. my $newText = wrap(4, "12345 67 8 9ab c de wxyz1 2 4 5 678");
  10. print "splitted String:\n";
  11. my @stringParts = split(/\n/, $newText);
  12. map {print "$_\n";} @stringParts;
  13.  
  14. sub wrap {
  15.     my ($maxLineLength, $oldText) = @_;
  16.  
  17.     my $regularExpression = '.{1,' . $maxLineLength . '}$|[^\\s]{' . $maxLineLength . '}|.{' . $maxLineLength . '}(?=\\s)|.{0,' . ($maxLineLength - 1) . '}\\s';    
  18.     my $newText = $oldText;
  19.     $newText =~ s/$regularExpression/$&\n/gs;
  20.  
  21.     return $newText;
  22. }
And here is the output when you run it:
splitted String:
Expand|Select|Wrap|Line Numbers
  1. splitted String:
  2. 1234
  3. 5 67
  4.  8
  5. 9ab
  6. c de
  7.  
  8. wxyz
  9. 1 2
  10. 4 5
  11. 678
Dec 9 '10 #11
rovf
41
So if this module is not installed on production environment

At least on Perl 5.10 or later, Text::Wrap is a standard module.
Dec 9 '10 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Yuriy | last post by:
Hi, Can anybody explain the following? Say I have the following source XML and XSLT (see below). No matter what this XSLT does. It is just a sample to show a problem. the idea is that XSLT...
1
by: Justin | last post by:
I have a string of dates seperated by commas and I need to seperate them and put them into a dropdown control. With the code below I am able to only remove the comma which results in one big long...
37
by: Anony | last post by:
Hi All, I'm trying to chunk a long string SourceString into lines of LineLength using this code: Dim sReturn As String = "" Dim iPos As Integer = 0 Do Until iPos >= SourceString.Length -...
2
by: CharChabil | last post by:
Using Vb.net 2005, I want to read each part in this string in an array (splitting the string) ----------- A1/EXT "BK82 LB73 21233" 105 061018 1804 ----------- That Code that i used is as follow:...
1
by: ronrsr | last post by:
I have a single long string - I'd like to split it into a list of unique keywords. Sadly, the database wasn't designed to do this, so I must do this in Python - I'm having some trouble using the...
5
by: Henrik | last post by:
The problem is (using MS Access 2003) I am unable to retrieve long strings (255 chars) from calculated fields through a recordset. The data takes the trip in three phases: 1. A custom public...
7
by: =?iso-8859-2?Q?K=F8i=B9tof_=AEelechovski?= | last post by:
How do I split a title attribute value into lines within the source code so that the paragraph gets reassembled by the browser when it is being displayed? Microsoft Internet Explorer 7 preserves...
12
by: manishsharma1 | last post by:
Hi, I have one long String like this: 015EnvironmentData1........ I want to read first three character from it and convert them to integer. This will be the length of the Name of the field...
6
by: huohaodian | last post by:
Hi, How can I define a long string variable in C# with multiple lines ? For example private string longName = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ...
14
by: spreadbetting | last post by:
I'm trying to split a string into an separate arrays but the data is only delimited by a comma. The actual data is one long string but the info is in a regular format and repeats after every five...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.