Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

130
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda