简体   繁体   中英

How to split string C# and ignore the incomplete word from the string

I want to make one general function. I want to store only complete word in array. Incomplete word should be ignore

input Sentence = "Twinkle twinkle little star"; 

I have an array size arr [19]. Here the condition is, if pointer come to "liitle", it will take the upto "lit", so i don't want the splited word in array then i have to drop the word "little". want complete words in an array. I want to generate the below output.

output sentence = "Twinkle twinkle"  

I try the below code, so what condition i have to add to ignore the split word

static void Main(string[] args)    
{
    string strSentence = "Twinkle twinkle little star";
    Console.WriteLine(strRead(strSentence));

    Console.ReadLine();
}

public static string strRead(string str)
{
    char[] arr = new char[19];
    string result3 = "";
    char[] sSplit = str.ToCharArray();
    for (int i = 0; i < arr.Length; i++)
    {           
        arr[i] = Convert.ToChar(sSplit[i]);
        result3 = result3 + arr[i].ToString();            
    }

    return result3;
}

Change the line char[] arr = new char[19]; to char[] arr = new char[15]; .

This will give the output you need.

The reason is because you have taken size as 19 and in loop it takes character from the sentence until the word "lit" and the length of the sentence "Twinkle twinkle lit" is 19 also.

Thanks.

A bit rough solution could look like this:

private static string CutOff(string input, int length)
{
    if ( length <= 0 ) throw new ArgumentOutOfRangeException(nameof(length));

    if (length >= input.Length) return input; //whole input
    var index = length - 1;
    if (char.IsWhiteSpace(input[index])) return input.Substring(0, length); //just cut off
    if (length < input.Length - 1 && !char.IsWhiteSpace(input[length]))
    {
        //word continues, search for whitespace character to the left
        while (length >= 0 && !char.IsWhiteSpace(input[length]))
        {
            length--;
        }
        if ( length < 0)
        {
            //single long word
            return "Can't cut off without breaking word";
        }
    }
    //cut off by length
    return input.Substring(0, length);
}

It handles all cases - if the string is too short, it returns the whole thing. If the cut-off index falls on whitespace character, we normally cut it. If it continues, we search for closest whitespace to the left. If we don't find any, we can't safely cut, as the input is a single long word.

For easier solution you could break down the input by spaces and then keep adding words while they fit the required length. However, my first solution is more efficient as it does not require additional memory and does not require reading the whole string.

private static string SplitCut( string input, int length)
{
    var words = input.Split(" ");
    StringBuilder builder = new StringBuilder();
    foreach (var word in words)
    {
        if ( builder.Length + word.Length <= length)
        {
            builder.Append(word);
        }
        else
        {
            //can't add more
            break;
        }
    }
    if (builder.Length == 0)
        return "Can't cut off without breaking word";
    return builder.ToString();
}

I'm not really sure what you're trying to achieve but maybe something like this could be useful to you?

var regex = new System.Text.RegularExpressions.Regex(@"^(.{0,19})\b(\s|$)");
var matches = regex.Match("Twinkle twinkle little star");

var success = matches.Success; // true
var result = matches.Groups[1]; // Twinkle twinkle

You could then parameterize the 19 for length (if that's something you want to do).

you can make something like that.

public static string strRead(string str,int charCount)
{
    string result3 = "";
    var words = str.Split(' ');
    var wordsCount = str.Length;
    var selectedWordsLength = 0;
    var spaceCharLength = 1;
    for (int i = 0; i < words.Length; i++)
    {
        var word = words[i];
        selectedWordsLength += word.Length + (spaceCharLength);
        if(selectedWordsLength >=charCount)
        {
            break;
        }
        result3 = result3 + word + " ";
    }
        return result3;
}

and use it like this

strRead(strSentence,19)

add an if-else condition in the loop,break if length of variable result3 is equal to 19

char[] arr = new char[19];
string result3 = "";
char[] sSplit = str.ToCharArray();

for (int i = 0; i< arr.Length; i++) {

arr[i] = Convert.ToChar(sSplit[i]);
result3 = result3 + arr[i].ToString();

`if(....) {//condition here, if result3.length is == 19 since it is a string you can count its length
  break;
 }`

}

This code will solve your problem. Let me know if there is something that it is not clear.

static void Main(string[] args)
{
    string input = "Twinkle twinkle little star";
    int length = 19;

    Console.WriteLine(CutOff(input,length));
}

private static string CutOff(string input, int length)
{
    var solution = input.Substring(0, Math.Min(input.Length, Math.Max(0, length)));
    if (solution.ElementAt(solution.Length-1) == ' ')
        return solution.Trim();

    if (input.ElementAt(solution.Length)!=' ')
    {
        var temp = solution.Split(' ');
        var result = temp.Take(temp.Count() - 1).ToArray();  //remove the last word
        return string.Join(" ", result);  //convert array into a single string
    }

    return solution;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM