wtm
wtm

Reputation: 166

c# Tab a string the right way

so...

I am creating a program, and at some point it writes:

sitename.com : 1
longersitename : 1
short.com : 1

and I want to write it like:

sitename.com   : 1
longersitename : 1
short.com      : 1

I tried adding \t, the problem is it will then make somethin like:

sitename.com      : 1
longersitename      : 1
short.com      : 1

How can I do this? Thanks!

Edit: Everyting is in the same string, code:

Console.WriteLine(allResults.Groups[1].Value.Replace("has: ", " : ").TrimEnd(Environment.NewLine.ToCharArray()).TrimStart(Environment.NewLine.ToCharArray()));

The " : " part is the part that needs to tab.

Edit: this is the string: (this is 1 string, with \n\r)

Unknown Site : 1  URL found.
Google Search : 3  URL found.
Youtube : 5  URL found.
Core  : 1  URL found.
Console : 88  URL found.

Upvotes: 0

Views: 232

Answers (3)

Scott Hannen
Scott Hannen

Reputation: 29222

Here's a quick sample that takes some key/value pairs and formats them with the sort of spacing you're describing:

var valuesOfVaryingLengths = "key: value, longer key: value, even much longer key: value";
var pairs = valuesOfVaryingLengths.Split(',')
    .Where(pair => pair.Contains(":")).ToArray()
    .Select(pair => pair.Split(':')).ToList();
var longest = pairs
    .Select(pair => pair[0]).Max(key => key.Length);
var padded = pairs.Select(
    pair => string.Concat(pair[0].Trim().PadRight(longest), ": ", pair[1].Trim()));
padded.ToList().ForEach(Console.WriteLine);

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186718

I suggest using Linq as well as regular expressions to obtain values:

  1. Split By new line

  2. Split by ':', in order to get rid of URL found. and obtain the number, use regular expression

  3. Format out name and value into single line, specify lengths and alignments

  4. Finally, combine all the lines back into a single string.

Implementation:

  String source = 
    "Unknown Site : 1  URL found.\r\n"+
    "Google Search : 3  URL found.\r\n" +
    "Youtube: 5  URL found.\r\n" +
    "Core: 1  URL found.\r\n" +
    "Console: 88  URL found.";

  //TODO: put actual lengths (instead of 15 and 3) in the formatting
  var target = source
    .Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
    .Select(line => line.Split(':'))
    .Select(items => String.Format("{0,-15}: {1,3}", 
       items[0].Trim(), 
       Regex.Match(items[1], "[0-9]+").Value));

  String result = String.Join(Environment.NewLine, target);

  ...

  // Unknown Site   :   1
  // Google Search  :   3
  // Youtube        :   5
  // Core           :   1
  // Console        :  88
  Console.Write(result); 

Upvotes: 1

Petr Vávro
Petr Vávro

Reputation: 1516

Using a monospaced font printing the string. The best way to align strings is using String.Format method

You will have to determine the longest site's name for this.

Upvotes: 0

Related Questions