Smartboy
Smartboy

Reputation: 1006

How to skip `\r \n ` in string

I am working on a simple converter which converts a text to another language,

suppose i have two textboxes and in 1st box you enter the word Index and press the convert button.
I will replace your text with this فہرست an alternative of Index in urdu language but i have a problem if you enter word index and gives some spaces or gives some returns then i get text of that textbox in c# like this Index \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n now how can i get rid of this i want to get simple Index always .
Thanks for answer and please feel free to comment if you have any question

Upvotes: 5

Views: 8798

Answers (4)

Tim Schmelter
Tim Schmelter

Reputation: 460108

Add all chars you want to ignore to the string:

var cleanChars = text.Where(c => !"\n\r".Contains(c));
string cleanText = new string(cleanChars.ToArray());

That works because string implements IEnumerable<char>.

Upvotes: 4

Steve
Steve

Reputation: 216293

This should suffice to remove whitespaces as defined by Char.IsWhiteSpace (blanks, newlines etc)

string wordToTranslate = textBox1.Text.Trim();

however, if your textbox contains multiple words then you should use a different approach

string[] words = textBox1.Text.Split((char[]) null, StringSplitOptions.RemoveEmptyEntries);
foreach(string wordToTranslate in words)
    ExecTranslation(wordToTranslate);

using Split with char[] null as separator allows to identify every whitespaces as valid word separator

Upvotes: 5

Botz3000
Botz3000

Reputation: 39610

Try using the Trim method if the new lines are only at the end of beginning:

input = input.Trim();

You can use Replace, if you want to remove new lines anywhere in the string:

// Replace line break with spaces
input = input.Replace("\r\n", " ");
// (Optionally) Combine consecutive spaces to one space (probalby not most efficient but should work)
while (input.Contains("  ")) { input = input.Replace("  ", " "); }

If you want to prevent newlines completely, most TextBox Controls have a property like MultiLine or similar, that, when set, prevents entering more than one line.

Upvotes: 9

Jakub Konecki
Jakub Konecki

Reputation: 46008

input.Replace(Environment.NewLine, string.Empty).Replace(" ", string.Empty);

User Replace to remove characters from the 'inside' of the string. Trim removes characters only at the begining and end of string.

Upvotes: 5

Related Questions