-1

In my application I want to send message to a device... the device accepts only 14 characters at a time, so if I have a string of 100 characters means I have to split 14 characters a time and send the message for that I tried to use this method

string input = "First sentence. Second sentence! Third sentence? Yes.";
string[] sentences = Regex.Split(input, @"(?<=[\.!\?])\s+");

foreach (string sentence in sentences) {
  Console.WriteLine(sentence);
}

The above sample code splits the sentences as I want but sometime it splits more than 14 characters

The tricky situation I am facing... the sentence should be below 14 characters and also it should be a complete sentence

Code should split the sentences and length should be below 14 characters can anyone help me.

Subramanian
  • 353
  • 5
  • 17
  • try following : string input = "First sentence. Second sentence! Third sentence? Yes."; while (input.Length > 0) { if(input.Length > 14) { Console.WriteLine(input.Substring(0,14)); input = input.Substring(14); } else { Console.WriteLine(input); input = ""; } } – jdweng Mar 13 '17 at 11:14
  • As long as the words are always separated by an space, it does not seem a difficult task. Just split by the space, and create a `List`, and only add the word if the lenght of the line is smaller that 14...If you want i can give you a code sample – Pikoh Mar 13 '17 at 11:52
  • @Pikoh Yes thats what I am trying now – Subramanian Mar 13 '17 at 12:11
  • @Subramanian i've put some code in my answer. Have a look and see it if matches your specifications – Pikoh Mar 13 '17 at 12:22

1 Answers1

0

I think this code would do what you want. For it to work, words must be always have a space between them to correct split them. You may have to change it depending on your specifications:

string input = "First sentence. Second sentence! Third sentence? Yes.";
string[] sentences = Regex.Split(input, @"(?<=[\.!\?])\s+");
List<string> lines = new List<string>();
string line = "";
foreach (string sentence in sentences)
{
    string[] words = sentence.Split(' ');
    foreach (string word in words)
    {
        if (line.Length + word.Length < 14)
            line += word + " ";
        else
        {
            lines.Add(line);
            line = word+ " ";
        }
    }
    lines.Add(line);
    line = "";
}

//Output: 

//First
//sentence
//Second
//sentence!
//Third
//sentence?
//Yes
Pikoh
  • 7,582
  • 28
  • 53