Moving a whole line string to the right - c#

const string Duom = "Text.txt";
char[] seperators = { ' ', '.', ',', '!', '?', ':', ';', '(', ')', '\t' };
string[] lines = File.ReadAllLines(Duom, Encoding.GetEncoding(1257));
for (int i = 0; i < lines.Length; i++)
{
string GLine = " " + lines[i];
GLine = Regex.Replace(GLine, #"\s+", " ");
GLine = GLine.PadRight(5, ' ');
Console.WriteLine(GLine);
}
Reads a text file, for each line it adds a whitespace at the start, removes all double and above whitespaces, and I want to move the line to the right , but it doesn't do anything.
Result :
Expected Result:

PadLeft and PadRight doesn't add characters to the start/end of your string if the specified length has already been reached.
From the docs for String.PadRight (emphasis mine):
Returns a new string that left-aligns the characters in this string by padding them on the right with a specified Unicode character, for a specified total length.
All of your strings are larger than 5, the specified total length, so PadRight/PadLeft won't do anything.
"Padding" the string is adding spaces (or some other character) so that the new string is at least as large as the number you want.
Instead, just manually add 5 spaces before your string.
GLine = " " + GLine;
Or more programmaticly:
GLine = new string(' ', 5) + GLine;

You could replace the body of your loop like this:
string GLine = new string(' ', 1 + i * 5) + Regex.Replace(lines[i], #"\s+", " ");
Console.WriteLine(GLine);
This will add 1 space and then 5 more spaces for each line.

for (int i = 0; i < lines.Count(); i++)
{
string GLine = new string(' ',5*i) + lines[i];
Console.WriteLine(GLine);
}
This should add 5 extra spaces for each line you have, which i believe is what you are trying to accomplish if i understand correctly.

You need to left pad a tab depending on how many lines of text you have. The best increment to use is the i variable.
string GLine = " " + lines[i];
change this to
string GLine = new String('\t', i) + lines[i];
By the way, PadLeft should work but keep in mind you need to execute it i times

Related

Count chars and words in text, can it be optimized?

I want to count chars in a big text, I do it with this code:
string s = textBox.Text;
int chars = 0;
int words = 0;
foreach(var v in s.ToCharArray())
chars++;
foreach(var v in s.Split(' '))
words++;
this code works but it seems pretty slow with large text, so how can i improve this?
You don't need another char-array, you can use String.Length directly:
int chars = s.Length;
int words = s.Split().Length;
Side-note: if you call String.Split without an argument all white-space characters are used as delimiter. Those include spaces, tab-characters and new-line characters. This is not a complete list of possible word delimiters but it's better than " ".
You are also counting consecutive spaces as different "words". Use StringSplitOptions.RemoveEmptyEntries:
string[] wordSeparators = { "\r\n", "\n", ",", ".", "!", "?", ";", ":", " ", "-", "/", "\\", "[", "]", "(", ")", "<", ">", "#", "\"", "'" }; // this list is probably too extensive, tim.schmelter#myemail.com would count as 4 words, but it should give you an idea
string[] words = s.Split(wordSeparators, StringSplitOptions.RemoveEmptyEntries);
int wordCount = words.Length;
You can do this in a single pass through without making a copy of your string:
int chars = 0;
int words = 0;
//keep track of spaces so as to only count nonspace-space-nonspace transitions
//it is initialized to true to count the first word only when we come to it
bool lastCharWasSpace = true;
foreach (var c in s)
{
chars++;
if (c == ' ')
{
lastCharWasSpace = true;
}
else if (lastCharWasSpace)
{
words++;
lastCharWasSpace = false;
}
}
Note the reason I do not use string.Split here is that it does a bunch of string copies under the hood to return the resulting array. Since you're not using the contents but instead are only interested in the count, this is a waste of time and memory - especially if you have a big enough text that has to be shuffled off to main memory, or worse yet swap space.
Do be aware that string.Split does on the other hand by default use a longer list of delimiters than just ' ', so you may want to add other conditions to the if statement.
You can simply use
int numberOfLetters = textBox.Length;
or use LINQ
int numberOfLetters = textBox.ToCharArray().Count();
or
int numberOfLetters = 0;
foreach (char letter in textBox)
{
numberOfLetters++;
}
var chars = textBox.Text.Length;
var words = textbox.Text.Count(c => c == ' ') + 1;

How to count only letters in a string?

At the next code I'm splitting text to words, inserting them into a table separately and counting the numbers of letters in each word.
The problem is that counter is also counting spaces at the beginning of each line, and give me wrong value for some of the words.
How can I count only the letters of each word exactly?
var str = reader1.ReadToEnd();
char[] separators = new char[] {' ', ',', '/', '?'}; //Clean punctuation from copying
var words = str.Split(separators, StringSplitOptions.RemoveEmptyEntries).ToArray(); //Insert all the song words into "words" string
string constring1 = "datasource=localhost;port=3306;username=root;password=123";
using (var conDataBase1 = new MySqlConnection(constring1))
{
conDataBase1.Open();
for (int i = 0; i < words.Length; i++)
{
int numberOfLetters = words[i].ToCharArray().Length; //Calculate the numbers of letters in each word
var songtext = "insert into myproject.words (word_text,word_length) values('" + words[i] + "','" + numberOfLetters + "');"; //Insert words list and length into words table
MySqlCommand cmdDataBase1 = new MySqlCommand(songtext, conDataBase1);
try
{
cmdDataBase1.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
This will be a simple and fast way of doing so:
int numberOfLetters = words[i].Count(word => !Char.IsWhiteSpace(word));
Another simple solution that will save you the above and rest of the answers here, will be to Trim() first, and than do your normal calculation, due your statement that it is happening just in the beginning of every line.
var words = str.Trim().Split(separators, StringSplitOptions.RemoveEmptyEntries);
Than all you will need is: (Without the redundant conversion)
int numberOfLetters = words[i].Length;
See String.Trim()
int numberOfLetters = words[i].Trim().ToCharArray().Length; //Calculate the numbers of letters in each word
instead of ' ' use '\s+' since it matches one or more whitespace at once, so it splits on any number of whitespace characters.
Regex.Split(myString, #"\s+");

how to count words correctly in text [duplicate]

This question already has answers here:
C# Word Count function
(5 answers)
Closed 8 years ago.
I want give my program a text and it count the words correctly
I tried to use an array to save words in it :
string[] words = richTextBox1.Text.Split(' ');
But this code has a problem and it is count the spaces in text
so I tried the following code :
string[] checkwords= richTextBox1.Text.Split(' ');
for (int i = 0; i < checkwords.Length; i++)
{
if (richTextBox1.Text.EndsWith(" ") )
{
return;
}
else
{
string[] words = richTextBox1.Text.Split(' ');
toolStripStatusLabel1.Text = "Words" + " = " + words.Length.ToString();
but now it wont work correctly .
I'd recommend using Regex here, using the 'word boundary' anchor
Otherwise your code may not correctly take into account things like Tabs and New Lines - \b will take care of that for you
var words = Regex
.Split("hello world", #"\b")
.Where(s => !string.IsNullOrWhiteSpace(s));
var wordCount = words.Count();
You can use the overload of String.Split with StringSplitOptions.RemoveEmptyEntries to ignore multiple consecutive spaces.
string text = "a b c d"; // 4 "words"
int words = text.Split(new char[]{}, StringSplitOptions.RemoveEmptyEntries).Length;
I'm using an empty char[] (you can also use new string[]{}) because that takes all white-space characters into account, so not only ' ' but also tabs or new-line characters.
I do not know why you wish to return if the textbox ends in " ". Maybe it should be a next or continue instead.
If multiple spaces is a possibility.
Regex myRege = new Regex(#"[ ]{2,}");
string myText = regex.Replace(richTextBox1.Text, #" ");
string[] words= myText.Split(" ");
toolStripStatusLabel1.Text = "Words" + " = " + words.Length.ToString();
Just for fun
private string[] GetCount(string bodyText)
{
bodyText = bodyText.Replace(" "," ");
if(bodyText.Contains(" ")
GetCount(bodyText)
return bodyText.Split(' ');
}
string[] words = GetCount(richTextBox1.Text)
toolStripStatusLabel1.Text = "Words" + " = " + words.Length.ToString();

Trimming with array of string

i want to create a simple program that i have a array of strings and for each string i want to check if it contains specified character, i want to remove it.first of all i replace the specified characters with space and when i tried to trim the spaces it doesn't work
Here it is my code
char[] arr = new char[] {' '};
for (int i = 0; i < words.Length; i++)
{
words[i] = words[i].Replace('0', ' ');
words[i] = words[i].Trim(arr);
}
If you want to remove all spaces, instead of words[i] = words[i].Trim(arr);, you can use:
words[i] = words[i].Replace(" ", string.Empty);
Personally, I would do this for your first removal (0) as well:
words[i] = words[i].Replace("0", string.Empty); // Remove all "0" characters
words[i] = words[i].Replace(" ", string.Empty); // Remove all spaces
Or, even:
words[i] = words[i].Replace("0", string.Empty).Replace(" ", string.Empty);
Trim() only removes leading and trailing spaces. It won't remove spaces in the middle of a string. There's really no need to do all that work though. You can make a single call to Replace() by calling the appropriate overload:
for(int i = 0; i < words.Length; i++)
words[i] = words[i].Replace("0", "");
and for people who like one-liners:
words = words.Select(i => i.Replace("0", "").Replace(" ", "")).ToArray();

How can I create a string in C# programmatically?

I have a string, and I want to add a number of spaces to the beginning of that string based on an int variable.
I want to do something like this:
int NumberOfTabs = 2;
string line = "my line";
string line = String.Format("{0}{1}", " " * NumberOfTabs, line);
...and now line would have 8 spaces
What is the easiest way to do this?
You can use the String(char, Int32) constructor like this:
string line = String.Format("{0}{1}", new String(' ', NumberofTabs * 4), line);
or a bit more efficient:
string line = String.Concat(new String(' ', NumberofTabs * 4), line);
or, a bit more concise :)
string line = new String(' ', NumberofTabs * 4).Concat(line);
A comment made a good point, if you want to actually have the tab character, just change the ' ' to '\t' and take out the * 4 like this:
string line = String.Concat(new String('\t', NumberofTabs), line);
int i=8;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(" ", i);
new string(' ', NumberOfTabs )
str = str.PadLeft(str.Length+tabs*4);
In C# strings are immutable. You should really use the stringbuilder class.
Code examples are listed in the link:
http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx
You could use something like this:
String.Empty.PadRight(NumberOfTabs)
You can add tabs at the beginning of your text like this:
line.PadLeft(NumberOfTabs, '\t');
\t being the escape character for "tab"
(Inserting a tab character into text using C#)
int NumberOfTabs = 2;
string line = "my line";
string results = line.PadLeft(line.Length + NumberOfTabs, ' ');
Not the best answer by any measure, but here's an amusing one, a little LINQ one-liner:
var result = new string(Enumerable.Repeat(' ', count).Concat("my line").ToArray());
You can create a new string containing a custom number of spaces. Unfortunately, there's no string multiplication like in Python (" " * 2). But you can multiply the number of spaces by 4 to get "tabs":
int numberOfTabs = 2;
string line = "my line";
string whitespaces = new string(' ', numberOfTabs * 4);
string s = whitespaces + line;

Categories

Resources