Q: Get characters from string and formatting.

  • Thread starter Thread starter Visual Systems AB \(Martin Arvidsson\)
  • Start date Start date
V

Visual Systems AB \(Martin Arvidsson\)

Hi!

I have a string, it could look like this

455 56 Gothenburg or 45556 Gothenburg

What i want to do is to separate the numbers from the text into two
different strings
and the numbers i would like to formate like ### ##.

My brain is just not giving me any direction on how to solve this :D

//Martin, Sweden
 
Visual said:
I have a string, it could look like this

455 56 Gothenburg or 45556 Gothenburg

What i want to do is to separate the numbers from the text into two
different strings
and the numbers i would like to formate like ### ##.

My brain is just not giving me any direction on how to solve this :D

Using a regular expression could be a good idea. Consider this code:

Match match = Regex.Match("455 56 Gothenburg",
@"(?<numpart1>\d{3})\s*(?<numpart2>\d{2})\s+(?<text>.*)");
if (match.Success) {
string newString = match.Groups["numpart1"].Value + " " +
match.Groups["numpart2"].Value + " " + match.Groups["text"].Value;
// Now newString contains the needed format.
}

This will work just the same whether you pass in the syntax "455 56
Gothenburg" or "45556 Gothenburg".


Oliver Sturm
 
Your question is not specific enough. You didn't describe the rules for the
format of the strings; you gave 2 possible examples. For example, could the
string in question look like this:

4 5 5 5 6 Gothenburg

or 45 556 Whatever

or 45556 Something with spaces

?

The best answer depends on the formatting rules for the source string. For
example, you could cover all possible bases by:

string source = "4 55 56 Gothenburg";
int i, len, pos = 0;
StringBuilder sb = new StringBuilder();
len = source.Length;
sb.Capacity = len;
for (i = 0; i < len; i++)
{
if (Char.IsDigit(source)
{
sb.Append(source);
if (++pos == 3) sb.Append(' ');
else if (pos == 5)
{
sb.Append(' ');
do (i++) while (i < len && Char.IsSeparator(source);
while (i < len) sb.Append(source);
}
}
}

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Big things are made up of
lots of little things.
 
Back
Top