Write list objects to new line with spaces inbetween - c#

I'm rubbish at explaining things so I'm just going to let the code do the talking. This is a section of code I have
PIDages.Sort();
lollist.WriteLine();
foreach (int a in PIDages)
{
lollist.Write(a + " ");
}
PIDages.Clear();
This code is repeated many times. At the moment it will output the each list on a new line in the following format
13*SPACE*
13 13*SPACE*
1 2 8*SPACE*
Is there an easy fix to not have the space character at the end of every line?

you can use the string.Join function
lollist.WriteLine(String.Join(" ", PIDages));
I'm currently not sure if a cast is necessary, in C# 2.0 the syntax would be
lollist.WriteLine(String.Join(" ", PIDages.Select(a => a.ToString()).ToArray());

You could first concatenate the string and then use Trim to get rid of any spaces at the start or the end of the string.
A little bit like that:
string result = String.Empty;
foreach (int a in PIDages)
{
result = result + a + " ";
}
result = result.Trim();
lollist.Write(result);

If you want to skip space at the end of string
You can try :
PIDages.Sort();
lollist.WriteLine();
string sResult = string.Empty;
foreach (int a in PIDages)
{
sResult += (a + " ");
}
lollist.Write(sResult.Trim());
PIDages.Clear();

Keep it simple?
bool add_space = false;
PIDages.Sort();
lollist.WriteLine();
foreach (int a in PIDages)
{
if (add_space)
lollist.Write(" ");
else
add_space = true;
lollist.Write(a);
}
PIDages.Clear();

Related

Going to the end of a substring in c#

The comment // go to end, I can't figure out how to cleanly end the substring :(
Is there a simpler way to go to the end of the substring rather than mathing out the number by myself? For more complex strings this would be too hard
string word = Console.ReadLine();
string[] lines = File.ReadAllLines(file);
using (var far = File.CreateText(resultfile))
{
foreach (string line in lines)
{
StringBuilder NewL = new StringBuilder();
int ind = line.IndexOf(word);
if (ind >= 0)
{
if (ind == 0)
{
NewL.Append(line.Substring(ind+ word.Length +1, // go to end);
}else{
NewL.Append(line.Substring(0, ind - 1));
NewL.Append(line.Substring(ind + word.Length + 1, // go to end));}
far.WriteLine(NewL);
}
else
{
far.WriteLine(line);
}
}
I don't know what more details the stackoverflow wants, anyone who can answer this pretty sure can clearly understand this simple code anyways.
You can use the String.Substring(int) overload, which automatically continues to the end of the source string:
NewL.Append(line.Substring(ind + word.Length + 1));
Retrieves a substring from this instance. The substring starts at a specified character position and continues to the end of the string.
It seems to me that you are just trying to remove a certain word from the loaded lines. If this is your task then you can simply replace the word with an empty string
foreach (string line in lines)
{
string newLine = line.Replace(word, "");
far.WriteLine(newLine);
}
Or even without an explicit loop with a bit of Linq
var result = lines.Select(x = x.Replace(word,""));
File.WriteAllLines("yourFile.txt", result);
Or, given the requirement to match an additional character after the word you can solve it with Regex.
Regex r = new Regex(word + ".");
var result = lines.Select(x => r.Replace(x, ""));
File.WriteAllLines("yourFile.txt", result);

How to remove certain characters

I'm trying to remove single vowels from a string, but not if a vowel is double same.
For example string
"I am keeping a foobar"
should print out as
"m keepng foobr"
I have tried everything but didn't come up with a solution so far.
Try:
Regex.Replace(input, #"([aeiou])\1", "");
Though for I am keeping a foobar, it will give you m keepng foobr, which is different to your required m keepng foobr, as you're stripped spaces out of your required result, too.
If you want to remove the extraneous spaces, then it's a three step operation: remove vowels; remove proceeding/trailing spaces; remove double spaces.
var raw = Regex.Replace(input, #"([aeiou])\1", "");
var trimmed = raw.Trim();
var final = trimmed.Replace(" ", " ");
You could try this logic:
loop trough string and check two by two characters
if (isBothVowelsAndEqual()) do nothing; else removeFirstChar();
EDIT:
public List<char> vowels = "AEIOUaeiou".ToList();
public bool isBothVowelsAndEqual(char first, char second)
{
return (first == second && vowels.Contains(first));
}
const string s = "I am keeeping a foobar";
string output=String.Empty;
for (int i = 0; i < s.Length-1; i++)
{
if (isBothVowelsAndEqual(s[i], s[i + 1]))
{
output = output + s[i] + s[i+1];
i++;
}
else
{
if (!vowels.Contains(s[i])) {
output += s[i];
}
}
}
Console.WriteLine(output.Trim());

Alternatively upper- and lowercase words in a string

I use Visual Studio 2010 ver.
I have array strings [] = { "eat and go"};
I display it with foreach
I wanna convert strings like this : EAT and GO
Here my code:
Console.Write( myString.First().ToString().ToUpper() + String.Join("",myString].Skip(1)).ToLower()+ "\n");
But the output is : Eat and go . :D lol
Could you help me? I would appreciate it. Thanks
While .ToUpper() will convert a string to its upper case equivalent, calling .First() on a string object actually returns the first element of the string (since it's effectively a char[] under the hood). First() is actually exposed as a LINQ extension method and works on any collection type.
As with many string handling functions, there are a number of ways to handle it, and this is my approach. Obviously you'll need to validate value to ensure it's being given a long enough string.
using System.Text;
public string CapitalizeFirstAndLast(string value)
{
string[] words = value.Split(' '); // break into individual words
StringBuilder result = new StringBuilder();
// Add the first word capitalized
result.Append(words[0].ToUpper());
// Add everything else
for (int i = 1; i < words.Length - 1; i++)
result.Append(words[i]);
// Add the last word capitalized
result.Append(words[words.Length - 1].ToUpper());
return result.ToString();
}
If it's always gonna be a 3 words string, the you can simply do it like this:
string[] mystring = {"eat and go", "fast and slow"};
foreach (var s in mystring)
{
string[] toUpperLower = s.Split(' ');
Console.Write(toUpperLower.First().ToUpper() + " " + toUpperLower[1].ToLower() +" " + toUpperLower.Last().ToUpper());
}
If you want to continuously alternate, you can do the following:
private static string alternateCase( string phrase )
{
String[] words = phrase.split(" ");
StringBuilder builder = new StringBuilder();
//create a flag that keeps track of the case change
book upperToggle = true;
//loops through the words
for(into i = 0; i < words.length; i++)
{
if(upperToggle)
//converts to upper if flag is true
words[i] = words[i].ToUpper();
else
//converts to lower if flag is false
words[i] = words[i].ToLower();
upperToggle = !upperToggle;
//adds the words to the string builder
builder.append(words[i]);
}
//returns the new string
return builder.ToString();
}
Quickie using ScriptCS:
scriptcs (ctrl-c to exit)
> var input = "Eat and go";
> var words = input.Split(' ');
> var result = string.Join(" ", words.Select((s, i) => i % 2 == 0 ? s.ToUpperInvariant() : s.ToLowerInvariant()));
> result
"EAT and GO"

How to parse a text removing a char

Let's start with that i have a txtProbe(textbox) and there i have 12-34-56-78-90. I want to parse them in different labels or textboxes ... For now just in one textbox - txtParse. I tried with that code - I'm removing the "-" and then tried to display them but nothing happens:
{
char[] delemiterChars = { '-' };
string text = txtProbe.Text;
string[] words = text.Split(delemiterChars);
txtParse.Text = text;
foreach (string s in words)
{
txtParse.Text = s;
}
}
EDIT:
I want to set the received information in different labels:
12-label1
34-label2
56-label3
78-label4
90-label5
You could just use String.Replace:
txtParse.Text = txtProbe.Text.Replace("-", " ");
The following 'll do the trick more "semantically":
var parsed = text.Replace("-", " ");
You might be changing the value too early in the Page Life Cycle (in the case of Web Forms), with regards to why you're not seeing the parsed value in the server control.
For your specific sample it seems that you could just replace '-' by ' '.
txtParse.Text = txtProbe.Text.Replace('-', ' ');
But in order to join an array of strings using a white space separator, you could use this
txtParse.Text = string.Join(" ", words);
Your logic is not appropiated for the task you're trying to acheive but just for learning purposes I'll write the correct version of your snippet
string separator = string.Empty; // starts empty so doesn't apply for first element
foreach (string s in words)
{
txtParse.Text += separator + s; // You need to use += operator to append content
separator = " "; // from second element will append " "
}
EDIT
This is for the case of using different labels
Label[] labelList = new Label[] {label1, label2, label3, label4, label5};
for (int i = 0; i < words.Length; i++)
{
labelList[i].Text = words[i];
}
You can use String.Join to join collection of strings as you want. In your case:
txtParse.Text = String.Join(" ", words);
You can use the delimiter character directly in .split('-') to return an array of strings representing that data you want.
Your problem is that you keep assigning s to the Text property. The end result will be the last s in your array.
You can use TextBox.AppendText() instead.
char[] delemiterChars = { '-' };
string text = txtProbe.Text;
string[] words = text.Split(delemiterChars);
txtParse.Text = text;
foreach (string s in words)
{
txtParse.AppendText(s + " ");
}
You can just put txtParse.Text = txtProbe.Text.Replace('-', " ");
Or by modifying your code:
char[] delemiterChars = { '-' };
string text = txtProbe.Text;
string[] words = text.Split(delemiterChars,StringSplitOptions.RemoveEmptyEntries);
foreach (string s in words)
{
txtParse.Text += " " + s;
}

C# fix sentence

I need to take a sentence in that is all on one line with no spaces and each new word has a captial letter EX. "StopAndSmellTheRoses" and then convert it to "Stop and smell the roses" This is my function that I have but I keep getting an argument out of range error on the insert method. Thanks for any help in advance.
private void FixSentence()
{
// String to hold our sentence in trim at same time
string sentence = txtSentence.Text.Trim();
// loop through the string
for (int i = 0; i < sentence.Length; i++)
{
if (char.IsUpper(sentence, i) & sentence[i] != 0)
{
// Change to lowercase
char.ToLower(sentence[i]);
// Insert space behind the character
// This is where I get my error
sentence = sentence.Insert(i-1, " ");
}
}
// Show our Fixed Sentence
lblFixed.Text = "";
lblFixed.Text = "Fixed: " + sentence;
}
The best way to build up a String in this manner is to use a StringBuilder instance.
var sentence = txtSentence.Text.Trim();
var builder = new StringBuilder();
foreach (var cur in sentence) {
if (Char.IsUpper(cur) && builder.Length != 0) {
builder.Append(' ');
}
builder.Append(cur);
}
// Show our Fixed Sentence
lblFixed.Text = "";
lblFixed.Text = "Fixed: " + builder.ToString();
Using the Insert method creates a new string instance every time resulting in a lot of needlessly allocated values. The StringBuilder though won't actually allocate a String until you call the ToString method.
You can't modify the sentence variable in the loop that is going through it.
Instead, you need to have a second string variable that you append all of the found words.
Here is the answer
var finalstr = Regex.Replace(
"StopAndSmellTheRoses",
"(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])|(?<=[^0-9])(?<x>[0-9])(?=.)",
me => " " + me.Value.ToLower()
);
will output
Stop and smell the roses
Another version:
public static class StringExtensions
{
public static string FixSentence(this string instance)
{
char[] capitals = Enumerable.Range(65, 26).Select(x => (char)x).ToArray();
string[] words = instance.Split(capitals);
string result = string.Join(' ', words);
return char.ToUpper(result[0]) + result.Substring(1).ToLower();
}
}

Categories

Resources