Adding a '-' to my string in C# - c#

I Have a string in the form "123456789".
While displaying it on the screen I want to show it as 123-456-789.
Please let me knwo how to add the "-" for every 3 numbers.
Thanks in Advance.

You can use string.Substring:
s = s.Substring(0, 3) + "-" + s.Substring(3, 3) + "-" + s.Substring(6, 3);
or a regular expression (ideone):
s = Regex.Replace(s, #"\d{3}(?=\d)", "$0-");

I'll go ahead and give the Regex based solution:
string rawNumber = "123456789";
var formattedNumber = Regex.Replace(rawNumber, #"(\d{3}(?!$))", "$1-");
That regex breaks down as follows:
( // Group the whole pattern so we can get its value in the call to Regex.Replace()
\d // This is a digit
{3} // match the previous pattern 3 times
(?!$) // This weird looking thing means "match anywhere EXCEPT the end of the string"
)
The "$1-" replacement string means that whenever a match for the above pattern is found, replace it with the same thing (the $1 part), followed by a -. So in "123456789", it would match 123 and 456, but not 789 because it's at the end of the string. It then replaces them with 123- and 456-, giving the final result 123-456-789.

You can use for loop also if the string length is not fixed to 9 digits as follows
string textnumber = "123456789"; // textnumber = "123456789012346" also it will work
string finaltext = textnumber[0]+ "";
for (int i = 1; i < textnumber.Length; i++)
{
if ((i + 1) % 3 == 0)
{
finaltext = finaltext + textnumber[i] + "-";
}
else
{
finaltext = finaltext + textnumber[i];
}
}
finaltext = finaltext.Remove(finaltext.Length - 1);

Related

What is the correct syntax of adding white space after specified number of characters using regex.replace()?

I'm using Regex.Replace to add a white space after every nth character into a string. I want to give an int variable(number of characters) after which white space should be added but It seems regular expression is not properly written for int variable and hence syntax error arises.
int num = 8;
string text="abcdefghijklmnop"
string result2 = Regex.Replace(text, ".{num}", "$0 "); //not working
this syntax is working
string result2 = Regex.Replace(text, ".{8}", "$0 ");
Regular expressions aren't parameterized in the way that you want, as far as I'm aware. Instead, you need to just build the pattern appropriately.
For most situations in modern C# I'd suggest using an interpolated string literal, which does work in this case, but requires the { and } to be doubled to avoid being treated as format specifiers. It may be more readable to just use string concatenation. So you can either use:
string result = Regex.Replace(text, ".{" + num + "}", "$0 ");
or if you're comfortable with { having different meanings in the same literal:
string result = Regex.Replace(text, $".{{{num}}}", "$0 ");
Not sure exactly what you want, but you may build the regex pattern using string concatenation:
int num = Int32.Parse(text_num);
string regex = ".{" + num + "}";
string result2 = Regex.Replace(text, regex, "$0 ");
TextArea1_trim_id.InnerText = result2;
This answer says nothing regarding whether your regex pattern makes any sense or is correct.
Alternative Linq solution (no regular expressions): we insert " " after each num characters (c)
int num = 8;
string text = "abcdefghijklmnop";
// "abcdefgh ijklmnop "
string result2 = string.Concat(text
.Select((c, i) => (i + 1) % num == 0
? c.ToString() + " "
: c.ToString()));
If we don't want to add trailing spaces (and thus we want "abcdefgh ijklmnop")
string result2 = string.Concat(text
.Select((c, i) => i < text.Length - 1 && (i + 1) % num == 0
? c.ToString() + " "
: c.ToString()));

Reverse Words at odd position only C#

This is my code. How can I edit it to show every word which is at the odd position ONLY to be reversed?
for (int i = input.Length - 1; i >= 0; i--)
{
if (input[i] == ' ')
{
result = tmp + " " + result;
tmp = "";
}
else
tmp += input[i];
}
result = tmp + " " + result;
Console.WriteLine(result);
Example input:
"How are you today"
to output:
"How era you yadot"
Based on the position of a word ['How' -> 0] do not reverse; [are -> 1 odd index] Reverse
You can achieve it with the help of LINQ:
var input = "hello this is a test message";
var inputWords = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var result = string.Join(" ",
inputWords.Select((w, i) =>
i % 2 == 0
? w
: new string(w.Reverse().ToArray())
));
Where w in the select is the word, and i is the index, starting at 0 for the first word. % is the modulus operator and gets the remainder. If i % 2 == 0 (i.e. i can be divided by 2 with no remainder), then the original is returned. If there is a remainder (odd) then the reversed word is returned. Finally, it's all wrapped up in a string.Join(" ", items); which turns it back into a normal string rather than an array of items.
Try it online
So far you have a string, like this:
string input = "I want to reverse all odd words (odd words only!).";
And you, naturally, want to perform the task. Now it's the main question what's an odd word?
If you mean word's position (I at position 0, want at 1 - should be reversed etc.)
then you can use regular expressions to match words and Linq to process them:
using System.Linq; // To reverse single word
using System.Text.RegularExpressions; // To match the words within the text
...
// Let's elaborate the test example: add
// 1. some punctuation - ()!. - to preserve it
// 2. different white spaces (spaces and tabulation - \t)
// to add difficulties for naive algorithms
// 3. double spaces (after "to") to mislead split based algorithms
string input = "I want to reverse all\todd words (odd words only!).";
int index = 0; // words' indexes start from zero
string result = Regex.Replace(
input,
"[A-Za-z']+", // word is letters and apostrophes
match => index++ % 2 == 0
? match.Value // Even words intact
: string.Concat(match.Value.Reverse())); // Odd words reversed
Console.WriteLine(result);
If you want to reverse the words with odd Length, i.e. I, all, odd then all you have to do is to change the condition to
match => match.Value % 2 == 0
Outcome:
I tnaw to esrever all ddo words (ddo words ylno!).
Please, notice, that the punctuation has been preserved (only words are reversed).
OP: Based on the position of a word ['How' -> 0] do not reverse; [are -> 1 odd index] Reverse
public static void Main()
{
string input = "How are you today Laken-C";
//As pointed out by #Dmitry Bychenko string input = "How are you today";
//(double space after How) leads to How are uoy today outcome
input = Regex.Replace(input, #"\s+", " ");
var inp = input.Split(' ').ToList();
for (int j = 0; j < inp.Count(); j++)
{
if(j % 2 == 1)
{
Console.Write(inp[j].Reverse().ToArray());
Console.Write(" ");
}
else
Console.Write(inp[j] + " ");
}
}
OUTPUT:
DEMO:
dotNetFiddle
try this is perfect working code..
static void Main(string[] args)
{
string orgstr = "my name is sagar";
string revstr = "";
foreach (var word in orgstr.Split(' '))
{
string temp = "";
foreach (var ch in word.ToCharArray())
{
temp = ch + temp;
}
revstr = revstr + temp + " ";
}
Console.Write(revstr);
Console.ReadKey();
}
Output: ym eman si ragas

Substring from specific sign to sign

I have a list of strings in format like this:
Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp
I need only the part from comma sign to the first dot sign.
For example above it should return this string: IScadaManualOverrideService
Anyone has an idea how can I do this and get substrings if I have list of strings like first one?
from comma sign to the first dot sign
You mean from dot to comma?
You can split the string by comma first, then split by dot and take the last:
string text = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
string result = text.Split(',')[0].Split('.').Last(); // IScadaManualOverrideService
Splitting strings is not what can be called effective solution. Sorry can't just pass nearby.
So here is another one
string text = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
var end = text.IndexOf(',');
var start = text.LastIndexOf('.', end) + 1;
var result = text.Substring(start, end - start);
Proof woof woof.
Bullet-proof version (ugly)
string text = "IScadaManualOverrideService";
//string text = "Services.IScadaManualOverrideService";
//string text = "IScadaManualOverrideService,";
//string text = "";
var end = text.IndexOf(',');
var start = text.LastIndexOf('.', (end == -1 ? text.Length - 1 : end)) + 1;
var result = text.Substring(start, (end == -1 ? text.Length : end) - start);
Insert this if hacker attack is expected
if(text == null)
return "Stupid hacker, die!";
string s = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
string s1 = s.Substring(0, s.IndexOf(","));
string s2 = s1.Substring(s1.LastIndexOf(".") + 1);
string input = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
int commaIndex = input.IndexOf(',');
string remainder = input.Substring(0, commaIndex);
int dotIndex = remainder.LastIndexOf('.');
string output = remainder.Substring(dotIndex + 1);
This can be written a lot shorter, but for the explanation i think this is more clear
sampleString.Split(new []{','})[0].Split(new []{'.'}).Last()
string s = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
string subStr = new string(s.TakeWhile(c => c != ',').ToArray());
string last = new string(subStr.Reverse().TakeWhile(c => c != '.').Reverse().ToArray());
Console.WriteLine(last); // output: IScadaManualOverrideService

Get all instances of sub-string one at a time?

If i have a string containing three 0 values, how would i grab them one by one in order to replace them?
the 0's could be located anywhere in the string.
i don't want to use regex.
example string to parse:
String myString = "hello 0 goodbye 0 clowns are cool 0";
right now i can only find the three 0 values if they are right next to each other. i replace them using stringToParse.Replace("0", "whatever value i want to replace it with");
I want to be able to replace each instance of 0 with a different value...
You can do something like this:
var strings = myString.Split('0');
var replaced = new StringBuilder(strings[0]);
for (var i = 1; i < strings.Length; ++i)
{
replaced.Append("REPLACED " + i.ToString());
replaced.Append(strings[i]);
}
pseudolang :
s = "yes 0 ok 0 and 0"
arr = s.split(" 0")
newstring = arr[0] + replace1 + arr[1] + replace2 + arr[2] + replace3
If you have control of these input strings, then I would use a composite format string instead:
string myString = "hello {0} goodbye {1} clowns are cool {2}";
string replaced = string.Format(myString, "replace0", "replace1", "replace2");
public string ReplaceOne(string full, string match, string replace)
{
int firstMatch = full.indexOf(match);
if(firstMatch < 0)
{
return full;
}
string left;
string right;
if(firstMatch == 0)
left = "";
else
left = full.substring(0,firstMatch);
if(firstMatch + match.length >= full.length)
right = "";
else
right = full.substring(firstMatch+match.length);
return left + replace + right
}
If your match can occur in replace, then you will want to track what index your upto and pass it in to indexOf.
Using LINQ and generic function to decouple replacement logic.
var replace = (index) => {
// put any custom logic here
return (char) index;
};
string input = "hello 0 goodbye 0 clowns are cool 0";
string output = new string(input.Select((c, i) => c == '0' ? replace(i) : c)
.ToArray());
Pros:
Char replacement logic decoupled from the string processing (actually LINQ query)
Cons:
Not the best solution from performance perspectives

How I can parse substring with regular expression ?

My example non-parsed data is
"8$154#3$021308831#7$NAME SURNAME#11$2166220160#10$5383237309#52$05408166#"
I want to parse data that is between $ and # strings.
I want to see result like that;
Between 8$ and # -> My data is 154,
Between 3$ and # -> My data is 021308831,
Between 7$ and # -> My data is NAME SURNAME,
Between 11$ and # -> My data is 2166220160,
Between 10$ and # -> My data is 5383237309,
Between 52$ and # -> My data is 05408166.
Thanks for your reply.
(\d+\$)(.*?)#
See it on Rubular
You will find the first part (e.g. 8$) in the capturing group 1 and the according data in the group 2.
The brackets are responsible, that the result is sotred in those capturing groups. The \d+ will match at least one digit. The .*? is a lazy match for everything till the next #.
class Program
{
static void Main(string[] args)
{
string text = "8$154#3$021308831#7$NAME SURNAME#11$2166220160#10$5383237309#52$05408166#";
string[] values = text.Split('$', '#');
for (var i = 0; i < values.Length - 1; i = i + 2)
{
Console.WriteLine("Between " + values[i] + "$ and # -> My data is " + values[i+1]);
}
Console.ReadLine();
}
}
You can split into array based on #.
With
String[] entries = data.Split('#');
you will get an arrays with "8$154", "3$021308831", etc.
Now you just work with the entries and split each one at the dollar sign:
String[] tmp = entries[0].Split('$');
So you get
tmp[0] = "8";
tmp[1] = "154";
Build in some checks and you will be happy. No need for regex here I suppose.
If you have "8$15$4#3$021308831" then you will get in tmp:
tmp[0] = "8"; // your key!
tmp[1] = "15"; // data part
tmp[2] = "4"; // data part ($ is missing!)
So you would have to concat all tmp above index 1:
StringBuilder value = new StringBuilder();
for(int i = 1; i < tmp.Length; i++)
{
if(i > 1) value.Append("$");
value.Append(tmp[i]);
}
Ok, taking stema's expression, which works.
using System.Text.RegularExpressions;
string nonParsed = "8$...";
MatchCollection matches = Regex.Matches(nonparsed, #"(\d+\$)(.*?)#");
StringBuilder result = new StringBuilder();
for(int i = 0; i < matches.Count; i++)
{
Match match = matches[i];
result.AppendFormat("Between {0} and #-> My data is {1}")
match.Groups[1].Value,
match.Groups[2].Value);
if (i < matches.Count - 1)
{
result.AppendLine(",");
}
else
{
result.Append(".");
}
}
return result.ToString();
Thanks to stema, this copes with the $ repeating within the value.
If you want to use regex this should do it.
\$([\w\d\s]+)\#
This will match betweel $ and #:
\$(.*?)#

Categories