Necesito una función que se vea así
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; }Créditos para dividir la cadena por conteo de caracteres y almacenar en una matriz de cadenas
Paso una cadena que es una oración y un Int que es el número máximo de caracteres permitidos en una oración.
Pero el problema es: no quiero que la oración se divida en medio de una palabra. En su lugar, divida antes de la última palabra posible y vaya a la siguiente oración.
No pude averiguar cómo hacer eso. ¿Alguien sabe cómo?
Gracias de antemano
Vamos a intentarlo. (siguiendo la segunda opción en el comentario de Juharr arriba)
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; }Aún así, esto tendrá problemas si hay una palabra con una longitud mayor que iterateCount