I'm trying to write strings with spaces into a listbox, and keep them aligned.
Here is the code:
List<String> treeNames = new List<String>();
int counter = 1;
treeNames.Add("Input ");
treeNames.Add("Output ");
treeNames.Add("Sequence Type ");
foreach (String currentData in treeNames)
{
listBox1.Items.Add(currentData + " - " + counter.ToString());
counter+=1;
}
Here's what I hope to achieve:
Input - 1
Output - 2
Sequence Type - 3
Instead, I'm getting:
Input - 1
Output - 2
Sequence Type - 3
Any ideas how can I align them?
foreach (String currentData in treeNames)
{
listBox1.Items.Add(String.Format("{0, -20} {1, 10}", currentData, ("- " + counter.ToString())));
counter += 1;
}
You can use String.PadRight method which returns a new string that left-aligns the characters in the string by padding them with spaces on the right for a specified total length.
Let's say you have 20 character maximum length for a name:
public String stringHighscore()
{
return name + name.PadRight(20 - name.Length) + "\t\t\t" + score.ToString();
}
If your name's length is 13, this will add 7 space characters. If your name's length is 9, this will add 11 space characters. That way all your name's lengths will equal 20 at the end.
Related
I want to add space between every 3 characters in a string in C#, but count from right to left.
For example :
11222333 -> 11 222 333
Answer by #Jimi from comments (will delete if they post their own)
var YourString = "11222333";
var sb = new StringBuilder(YourString);
for (int i = sb.Length -3; i >= 0; i -= 3)
sb.Insert(i, ' ');
return sb.ToString();
The benefit of this algorithm appears to be that you are working backwards through the string and therefore only moving a certain amount on each run, rather than the whole string.
If you are trying to format a string as a number according to some locale conventions you can use the NumberFormat class to set how you want a number to be formatted as a string
So for example
string input = "11222333";
NumberFormatInfo currentFormat = new NumberFormatInfo();
currentFormat.NumberGroupSeparator = " ";
if(Int32.TryParse(input, NumberStyles.None, currentFormat, out int result))
{
string output = result.ToString("N0", currentFormat);
Console.WriteLine(output); // 11 222 333
}
The following recursive function would do the job:
string space3(string s)
{
int len3 = s.Length - 3;
return (len <= 0) ? s
: (space3(s.Substring(0, len3)) + " " + s.Substring(len3));
}
C# 8.0 introduced string ranges. Ranges allow for a more compact form:
string space3(string s)
{
return (s.Length <= 3) ? s
: (space3(s[..^3]) + " " + s[^3..]);
}
Using Regex.Replace:
string input = "11222333";
string result = Regex.Replace( input, #"\d{3}", #" $0", RegexOptions.RightToLeft );
Demo and detailed explanation of RegEx pattern at regex101.
tl;dr: Match groups of 3 digits from right to left and replace them by space + the 3 digits.
The most efficient algorithm I can come up with is the following:
var sb = new StringBuilder(YourString.Length + YourString.Length / 3 + 1);
if (YourString.Length % 3 > 0)
{
sb.Append(YourString, 0, YourString.Length % 3);
sb.Append(' ');
}
for (var i = YourString.Length % 3; i < YourString.Length; i += 3)
{
sb.Append(YourString, i, 3);
sb.Append(' ');
}
return sb.ToString();
We first assign a StringBuilder of the correct size.
Then we check to see if we need to append the first one or two characters. Then we loop the rest.
dotnetfiddle
This question already has answers here:
Split - Index was outside the bounds of the array
(7 answers)
Closed 4 years ago.
This code should basically split the user input into its component letters and then output the 1st, 3rd and 5th letter in the array
bool greater = false;
Console.WriteLine("Enter your name: ");
string userName3 = Console.ReadLine();
while (greater = false)
{
if (userName3.Length >= 5)
{
greater = true;
}
else
{
Console.WriteLine("The name must be 5 characters or more");
}
}
string[] userNameArr = userName3.Split();
Console.WriteLine(userNameArr[0] + " " + userNameArr[2] + " " + userNameArr[4]);
When I run the last line causes an error saying
Index was outside the bounds of the array
Why is this and how can I fix it?
Split() doesn't split into char it splits by detecting and spliting by WhiteSpace characters into a array of strings.
If you want to get the characters, access the input string by index char firstChar = userName3[0];
Console.WriteLine(userName3[0] + " " + userName3[2] + " " + userName3[4]);
instead of
string[] userNameArr = userName3.Split();
Console.WriteLine(userNameArr[0] + " " + userNameArr[2] + " " + userNameArr[4]);
Sidenote:
replace while (greater = false) with while (!greater) or while (greater == false) since you want to do a comparison instead of a assingment
This should work:
bool greater = false;
while (greater == false)
{
Console.WriteLine("Enter your name: ");
string userName3 = Console.ReadLine();
if (userName3.Length >= 5)
{
greater = true;
}
else
{
Console.WriteLine("The name must be 5 characters or more");
}
}
string[] userNameArr = userName3.Split();
Console.WriteLine(userNameArr[0] + " " + userNameArr[2] + " " + userNameArr[4]);
The line:
while (greater = false)
Actually assigns false to greater, meaning you will never leave the loop. Further, you need the ReadLine inside the loop so that the user will be prompted again
String is array of char, so to get specific character use indexing instead of split()
for e.g. To get 5 letter from string use userNameArr[4].
This can be correct way to read characters from string
using System;
public class Program
{
public static void Main()
{
bool greater = false;
Console.WriteLine("Enter your name: ");
string userName3 = Console.ReadLine();
while (greater == false)
{
if (userName3.Length >= 5)
{
greater = true;
}
else
{
Console.WriteLine("The name must be 5 characters or more");
}
}
//Indexing to string is used to get letters from string
Console.WriteLine(userName3[0] + " " + userName3[2] + " " + userName3[4]);
}
}
Implemenation: DotNetFiddler
userName3.Split() splits the user name on spaces by default, so if username is phuzi then splitting will result in an array with a single item ["phuzi"] then only userNameArr[0] is valid. Any attempt to acces anything else will result in the error you're seeing
This is happening because the array does not contain this index.
The line
string[] userNameArr = userName3.Split();
You want to split by what ?
What I am trying to do is if user input four characters like 0500, I want to add ":" after second character so it becomes 05:00. From trial and error it does't seems to insert correctly.
So part of my codes is
string timeInput = Console.ReadLine();
string[] timeSplit = timeInput.Split(':');
if(timeInput.Length == 4) { // if string = four
timeInput = timeInput.Insert(1, ":");
}
You can't split the string by ':' if your input doesn't contain any ':'. So you don't need the variable timeSplit. You can do it like this:
string timeInput = Console.ReadLine();
if (timeInput.Length == 4) // if input = "0500" -> true
timeInput = timeInput.Insert(2, ":");
Console.WriteLine(timeInput); // Output: 05:00
With timeInput.Insert(1, ":") you would get "0:500" as output.
replace
timeInput = timeInput.Insert(1, ":");
with
timeInput = timeInput.Insert(2, ":");
to insert the : at the second index
string 0 5 0 0
index 0|1|2|3|4
A single character in a string is called a char
Although the length of the string is 4 the indexing starts with 0!
string timeInput = "0500"
When you index it it would look like this:
timeInput[0] -> 0
timeInput[1] -> 5
timeInput[2] -> 0
timeInput[3] -> 0
this is why you need to put the : on position 2
if(timeInput.Length == 4) // if string = four
{
timeInput = timeInput.Insert(2, ":");
}
The first argument of Insert method is the index number where you want to insert any character, after two digit the index number is 2 so It should be 2 instead 1
timeInput = timeInput.Insert(2, ":");
and why do you you spliting the input using : where you haven't inseted : into it? splite after innsert : is the correct one I guess
string timeInput = Console.ReadLine();
if(timeInput.Length == 4)
{ // if string = four
timeInput = timeInput.Insert(2, ":");
}
string[] timeSplit = timeInput.Split(':');
I'm using C#, and have the following string text value:
get directions from Sydney to Melbourne
And this is the code that I have at the moment to try and get the text that appears between From and To
String fromDestination = InputTextbox.Text;
if (fromDestination.Contains("from"))
{
fromDestination = fromDestination.Substring(fromDestination.IndexOf("from") + 5, fromDestination.IndexOf("to") - 3);
}
That code removes the word "from" from the returned value, but I cannot work out how to get ride of the "to". The output at the moment is:
sydney to Melb
Thanks for any help.
Here's another possible route (lolpun)..
You can split via "from" and "to". Each part is created for you then:
var str = "get directions from Sydney to Melbourne";
var parts = str.Split(new string[] { "from", "to" }, StringSplitOptions.None); // split it up
var from = parts[1]; // index 1 is from
var to = parts[2]; // index 2 is to
Console.WriteLine(from); // "Sydney"
Console.WriteLine(to); // "Melbourne"
The second parameter to pass to the Substring method is the number of chars to extract from the instance string, not another position
String fromDestination = InputTextbox.Text;
int pos = fromDestination.IndexOf(" from ");
if(pos >= 0)
{
int pos2 = fromDestination.IndexOf(" to ", pos);
if(pos2 > -1)
{
int len = pos2 - (pos + 6);
fromDestination = fromDestination.Substring(pos+6, len);
}
}
Notice that I have changed the search strings adding a space before and after from and to. This is a precautional measure required to avoid false positives when a city name contains 'to' as part of its name or if there is another from embedded in the text before the actual starting from
If the string is always the same I would suggest a simple string split.
string fromDestination = InputTextbox.Text.Split(' ')[3];
You can also use regular expressions:
String fromDestination = "get directions from Sydney to Melbourne";
var match = Regex.Match(fromDestination, #"(?<=from\s).*(?=\sto)");
if (match.Groups.Count > 0)
fromDestination = match.Groups[0].Value;
Substring(startIndex, length)
for compute the length you should try to fromDestination.Length - fromDestination.IndexOf(" to ")
fromDestination.Substring(fromDestination.IndexOf(" from ") + 5, fromDestination.Length - fromDestination.IndexOf(" to "));
This will get you the string "Sydney Melbourne":
string fromDestination = "get directions from Sydney to Melbourne";
string result = fromDestination.Substring(fromDestination.IndexOf("from") + 5).Replace("to", "");
By the look you probably would be better off replacing the textbox for 2 comboboxes,each with their items filled by a predefined list of available cities so the user cannot enter any typos for example and you just react to the selectedindex of the combobox...
I want to insert a space every 34 characters in a string
public string MySplit()
{
string SplitThis = "aaaaaaaaaaaa"; // assume that string has more than 34 chars
string[] array = new string[SplitThis .Length / 34];
for (int i = 1; i <= array.Length; i++)
{
SplitThis .Insert(i * 34, " ");
}
return SplitThis;
}
when I quickwatch "SplitThis .Insert(i * 34, " ");" I can see the space but the resultant string do not show the space. Why?
You are throwing away the result of the insert
Try
SplitThis = SplitThis.Insert(i*34, " ");
But there might be other logic errors in your code because you are amending the same string as you are working one and have calculated the number of iterations based on the length of the string, which is ignoring the fact that the length of the string is changing.