4

I have a long string, and this string must break at the 15th character or earlier.

In the example string

This must break right here

the 15th character is the letter 'k', so check if it is one of { ' ' , '.', ',' }. If it is, break the line in this position, otherwise check the preceding character until it can break. In the example it can break at character 10.

My code is only working if I can break on only one character in the equals clause:

char break = ' ';

If I use an array of possible characters (char[] canBreak = { ' ' , '.', ',' };), it doesn't work.

Here is my code that doesn't work, I think the problem is in the Equals:

char[] canBreak = { ' ' , '.', ',' };
char break = ' ';

while (!fullMsg[breakValue].Equals(canBreak))
{
    breakValue = breakValue - 1;
}

If I use only one char instead of char[] it works:

char[] canBreak = { ' ' , '.', ',' };
char break = ' ';

while (!fullMsg[breakValue].Equals(break))
{
    breakValue = breakValue - 1;
}

What am I doing wrong?

Callum Watkins
  • 2,844
  • 4
  • 29
  • 49
Delfanor
  • 77
  • 6
  • One character is not equal to an array of characters. So the condition in while will always return false. That's why it is not working. – Chetan Jan 19 '21 at 20:29
  • You should use following condition in while. `while(Array.IndexOf(canBreak, fulMsg[breakValue]) >=0)` – Chetan Jan 19 '21 at 20:31
  • https://stackoverflow.com/questions/7867377/checking-if-a-string-array-contains-a-value-and-if-so-getting-its-position – Chetan Jan 19 '21 at 20:33
  • Does this answer your question? [Check if a value is in an array (C#)](https://stackoverflow.com/questions/13257458/check-if-a-value-is-in-an-array-c) – Callum Watkins Jan 20 '21 at 05:20

1 Answers1

4

You should use canBreak.Contains(fullMsg[breakValue]) to check if your char is one of ' ' , '.', ','.

char[] canBreak = { ' ' , '.', ',' };

while (!canBreak.Contains(fullMsg[breakValue]))
{
    breakValue = breakValue - 1;
}

This uses Enumerable.Contains<TSource>(IEnumerable<TSource>, TSource) from System.Linq.

Callum Watkins
  • 2,844
  • 4
  • 29
  • 49
godot
  • 3,422
  • 6
  • 25
  • 42