1

Hello every technical elite, I'm a rookie in C#. This is my first time asking questions on stackoverflow, I'm a Chinese, my english is poor.

I am trying to make my C# application communicate with a digital scale via rs232 by using SerialPort class in .net.

I want insert a dot "." in a string ,I received the string use:(buf[3].ToString("X2"),the string is a number between 00~99,I want insert a dot in the number.How to do ?

Thanks a lot for any help.

Baz
  • 36,440
  • 11
  • 68
  • 94
user1602169
  • 29
  • 1
  • 4
  • It it always in the format {one character}{two digits} ? Also I have to say your English is very good. – asawyer Aug 27 '12 at 12:17
  • [How to: Concatenate Multiple Strings](http://msdn.microsoft.com/en-us/library/ms228504.aspx), [What's the best string concatenation method using C#?](http://stackoverflow.com/questions/21078/whats-the-best-string-concatenation-method-using-c), [Strings (C# Programming Guide)](http://msdn.microsoft.com/en-us/library/ms228362(v=vs.100).aspx)... – CodeCaster Aug 27 '12 at 12:18
  • 4
    Please tell what is input and what is desired output – Nikhil Agrawal Aug 27 '12 at 12:18
  • Thank you for you helps,I know how to solve the problem already. – user1602169 Aug 28 '12 at 00:53

5 Answers5

2

If you want to insert a string (in this case ".") into another, you can use the String.Insert method:

"99".Insert(1, ".") // results in "9.9"

In your case probably:

string result = buf[3].ToString("X2").Insert(1, ".");

If you just want to append a dot, you can just use the + operator:

buf[3].ToString("X2") + "."; 
Botz3000
  • 39,020
  • 8
  • 103
  • 127
2

You can also use Regex

string ss = buf[3].ToString("X2");
Regex.Replace("(\d)(\d)",ss,"$1.$2");
Anirudha
  • 32,393
  • 7
  • 68
  • 89
1

If the string always have 2 characters in it ( Ex :07 / 10 /26), you can get the first and second character by Substring function and do a string concatenation with a dot in between.

string ss = buf[3].ToString("X2");  
string result= ss.Substring(0, 1) + "." + ss.Substring(1, 1);
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • Thank you very much !!!!!Your answer to help me solve the problem,I have tried four days.Thanks again for everyone. – user1602169 Aug 28 '12 at 00:51
1
String sringToInstert = buf[3].ToString("X2");
sringToInstert.Insert(0,".");

Where 0 is the starting Index (Where you want to put the dot).

And "." is what you want to put.

For starting index 0 the result will be = .99

And For starting index 1 the result will be = 9.9

ygssoni
  • 7,219
  • 2
  • 23
  • 24
-4

string newStr = oldStr[0]+"."+oldStr[1];

RIRAJAT
  • 40
  • 1