Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
Split sentence if it has certain number of characters

I need a function that looks like this

static IEnumerable<string> GetSplittedSentences(string str, int iterateCount)
{
    var words = new List<string>();

    for (int i = 0; i < str.Length; i += iterateCount)
        if (str.Length - i >= iterateCount) 
            words.Add(str.Substring(i, iterateCount));
        else 
            words.Add(str.Substring(i, str.Length - i));

    return words;
}

Credits to Split string by character count and store in string array

I pass in a string that is a sentence, and an Int which is the max number of characters allowed in a sentence.

But the issue is: I don't want the sentence to be split in middle of a word. Instead split before the last possible word and go to the next sentence.

I couldn't figure out how to do that. Does anybody know how?

Thank you in advance

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Let's try it. (following the second option in the Juharr comment above)

static IEnumerable<string> GetSplittedSentences(string str, int iterateCount)
{
    var words = new List<string>();
    int i = 0;
    while(i < str.Length)
    {
        // Find the point where the split should occur
        int endSentence = i+iterateCount;
        if (endSentence <= str.Length)
        {
            // Go back to find a space
            while(str[endSentence] != ' ')
                endSentence--;
         
            // Take the string before the space 
            words.Add(str.Substring(i, endSentence-i));

            // Position the start point to extract the next block
            i = endSentence+1;
        }
        else
        {
            words.Add(str.Substring(i, str.Length - i));
            i = str.Length; // Force the loop to exit
        }
    }
    return words;
}

Still this will have problems if there is a word with a length bigger than iterateCount

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!