Inserting dashes into string - c#

I would like to know how I could insert dashed into various points into a string?
I have a string that is 32 characters long
I need dashes in various places
8-4-4-4-12
8 characters - 4characters... and so on till string is complete.
I tried REGEX but can only get it to add dashes at regular intervals
string newString = Regex.Replace(currentEPC, ".{6}", "$0-");
I am trying to parse a string as a Guid, but my string does not contain dashes, which it needs to be converted to the Guid.

I am trying to parse a string as a Guid, but my string does not contain dashes, which it needs to be converted to the Guid.
No, it doesn't:
Guid g = Guid.Parse("084c1bfd133d403384e1c02113b52f8c");
This will parse the GUID for you. If you want to have it in a string representation with dashes:
string s = g.ToString();

As Patrick has shown, you don't need to insert the dashes to parse the string to Guid.
However, if you need this method anyway you can use:
public static string InsertStrings(string text, string insertString, params int[] rangeLengths)
{
var sb = new StringBuilder(text);
var indexes = new int[rangeLengths.Length];
for (int i = 0; i < indexes.Length; i++)
indexes[i] = rangeLengths[i] + indexes.ElementAtOrDefault(i-1) + insertString.Length;
for (int i = 0; i < indexes.Length; i++)
{
if(indexes[i] < sb.Length)
sb.Insert(indexes[i], insertString);
}
return sb.ToString();
}
Usage:
string guidString = "36b1dbc650c6407098247f87790144ff";
guidString = InsertStrings(guidString, "-", 8, 4, 4, 4, 12);

Related

I would like to parse string to objet in c# micro framework

I need to parse this string
"+CMGL: 1,\"REC READ\",\"+420731177370\",\"\",\"2015/03/21 11:26:10+04\""
and I would like to parse for
id = 1, number = +420731177370, date = 2015/03/21 11:26:10+04\
Could you please help me how to do it without Regex because I have got an old version of micro framework.
My code is
for (int i = 0; i < sentences.Length; i += 2)
{
string[] test = sentences[i].Split(',');
for (int j = 1; j < test.Length; j++)
{
//to do stuff
}
}
to do stuff where i need to replace \"xxxxx\" to xxxx
Perhaps something like this will point you in the right direction. Just be aware that while the code below works well for the string in your original post, should that string change it might not work as well since it's relying on character counts as opposed to regexes.
var Source = "+CMGL: 1,\"REC READ\",\"+420731177370\",\"\",\"2015/03/21 11:26:10+04\"";
var SplitSource = Source.Split(',');
String ID = SplitSource[0].ToString().Remove(0, 6); //good
String Number = SplitSource[2].Replace("\"", ""); //good
String Date = SplitSource[4].Replace("\"", ""); //good

How to replace every char in a string value with the next char?

If I have a string variable like this:
string f = "ABC";
I want to make it like this:
f="CDE"
This means that I want to take every char in this string and increase it to the next 2 values, if I have 'a' I want to change it to 'c' and so on.
Following will increment the character to + 2, Not sure what you want when then characters are ending character in the alphabets.
string f = "ABC";
string result = new string(f.Select(r =>(char) (r + 2)).ToArray());
For string ABC result will be CDE, but for string XYZ result will be Z[\
All you need to do is get the individual char from the string e.g.
string a = "aba";
char b = a[0]; //the value is equal to 'a'
Console.WriteLine((char)((int)b + 1));
then convert the char into an int and increament it then convert it back to a char
You can convert the string to a char[], modify each char as needed, and convert the result back to a string as follows:
char[] chars = "ABC".ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
chars[i] += (char)2;
}
string result = new string(chars);
// result == "CDE"

Split 16 digit string into 4 parts and store them in an array in C#

I have a string composed of 16 digits (a hexadecimal number), which will be entered in a textbox as one large number. For example, '1111222233334444".
I need to
read this number in,
divide it into four groups, such as 1111 2222 3333 4444.
store the groups into four variables, or an array
I have found some methods to do this, but they just write to console. So after the user enters that data, I need to have something like:
string first = 1111;
string second = 2222;
string third = 3333;
string fourth = 4444.
Any help is appreciated!
You can do it with substring.
string strNumber = "1111222233334444";
string []strArr = new string[4];
for(int i=0; i < 4; i++)
{
strArr[i] = strNumber.Substring(i*4, 4);
}
Here it is:
string initial_string = TextBox1.Text; //read from textbox
string [] number = new string[4];
number[0] = initial_string.Substring(0,4);
number[1] = initial_string.Substring(4,4);
number[2] = initial_string.Substring(8,4);
number[3] = initial_string.Substring(12,4);
You can use Regex to do it in a single line:
var res = Regex.Split(str, "(?<=\\G\\d{4})");
NOTE: This works fine under Microsoft .NET, but does not work with Mono's implementation of Regex.

Convert a string/integer to superscript in C#

Is there a built in .NET function or an easy way to convert from:
"01234"
to:
"\u2070\u00B9\u00B2\u00B3\u2074"
Note that superscript 1, 2 and 3 are not in the range \u2070-\u209F but \u0080-\u00FF.
EDIT: I hadn't noticed that the superscript characters weren't as simple as \u2070-\u2079. You probably want to set up a mapping between characters. If you only need digits, you could just index into a string fairly easily:
const string SuperscriptDigits =
"\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079";
Then using LINQ:
string superscript = new string(text.Select(x => SuperscriptDigits[x - '0'])
.ToArray());
Or without:
char[] chars = text.ToArray();
for (int i = 0; i < chars.Length; i++)
{
chars[i] = SuperscriptDigits[chars[i] - '0'];
}
string superscript = new string(chars);

Split a string containing 16 digits into 4 groups

If you take a look at the plastic in your wallet the 16 digit credit card number is broken into 4 groups of 4. Im trying to do the same thing,
Currently I have a string that has 16 digits but is formed as 1 single number. How can I add a " " after the 4th 8th & 12th number?
Any tips would be really helpful.
Thanks
var number = 1234567890123456;
number.ToString( "0000-0000-0000-0000" );
Try something similar to this answer, using a NumberFormatInfo:
NumberFormatInfo format = new NumberFormatInfo();
format.NumberGroupSeparator = " ";
format.NumberGroupSizes = new[] { 4 };
format.NumberDecimalDigits = 0;
Use as:
long number = 7314787188619939;
string formatted = number.ToString("n", format);
Console.WriteLine(formatted);
Or, if you're dealing with a string, you may choose can use a regex for a quick string manipulation. This will be easy to adapt to other characters:
string str = "7314787188619939";
str = Regex.Replace(str, "(?!^).{4}", " $0" ,RegexOptions.RightToLeft);
string number = "1234567890ABCDEF";
int counter = 0;
var result = number
.GroupBy(_ => counter++ / 4)
.Select(g => new String(g.ToArray()));
There are many answers. Given a string s=1234567890123456 the easiest might be to create a StringBuilder and append it. Untested code example below.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i += 4)
{
sb.append(s.Substring(i, 4)); // Append these 4
if (i != s.Length - 4)
sb.append(" "); // append a space for all but the last group
}
Console.WriteLine(sb.ToString());
You may try something like this, an extension method
public static IEnumerable<String> SplitToParts(this String forSplit, Int32 splitLength)
{
for (var i = 0; i < forSplit.Length; i += splitLength)
yield return forSplit.Substring(i, Math.Min(splitLength, forSplit.Length - i));
}
string s ="1234123412341234";
s.SplitToParts(4) should do the trick
Hope this works !
Or if working with MD5 hashes, you could use an implementation like so...
public string exHashMd5(string data)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(data));
byte[] result = md5.Hash;
StringBuilder str = new StringBuilder();
for (int i = 0; i < result.Length; i++)
{
str.Append(result[i].ToString("X2"));
}
/// The implementation like so. (Below)
NumberFormatInfo format = new NumberFormatInfo();
format.NumberGroupSeparator = " ";
format.NumberGroupSizes = new[] { 8 };
format.NumberDecimalDigits = 0;
string rstr = str.ToString();
rstr = Regex.Replace(rstr, "(?!^).{8}", " $0", RegexOptions.RightToLeft);
return rstr.ToString();
/// At the end you get yourself a nice 4 way split.
/// Test it out. have a go with chucking it into a
/// MessageBox.Show(exHashMd5("yourstring"));
}
/// Could even go one further and add
string hashtext;
string newline = Enviroment.Newline;
hashtext = exHashMd5("yourtext");
/// Then you do a simple command.
MessageBox.Show(hashtext + newline + hashtext);
/// Nice four way again. complex but yet made simple.
To work out what you need it to do, use maths. seriously, its mathematical. divide the amount of characters, till you are able to get a sum that equals four. for example, 32 / 8 = 4. then this will give you the four way split you need. basic maths. basic. basic. basic.

Categories