469,306 Members | 1,791 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,306 developers. It's quick & easy.

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 4595
numberwhun
3,503 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

Post your reply

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

Similar topics

1 post views Thread by Justin | last post: by
2 posts views Thread by CharChabil | last post: by
1 post views Thread by ronrsr | last post: by
7 posts views Thread by =?iso-8859-2?Q?K=F8i=B9tof_=AEelechovski?= | last post: by
12 posts views Thread by manishsharma1 | last post: by
6 posts views Thread by huohaodian | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by suresh191 | last post: by
1 post views Thread by Geralt96 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.