0

I have strings like these:

azu3zS1YdQBF75qmp4oyi1/ttG6/ikOSkZZCdgAYGw2x8A4YBILnZ6lOhIRNgQJEcH56pqnrb8Y=

and I do not know the exact length of them so I want a function to change any strinng to a string of 20 characters.

Ralt
  • 2,084
  • 1
  • 26
  • 38
amirtutunchi
  • 190
  • 1
  • 8

2 Answers2

3

Try like this:

var x= str== null 
        ? string.Empty 
        : str.Substring(0, Math.Min(20, str.Length));
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • thanks a lot Substring work how could i get back the original String – amirtutunchi May 27 '15 at 07:14
  • 1
    @amirbt your original string will remain same in `str` – Shaharyar May 27 '15 at 07:15
  • 1
    @amirbt you don't need to get it back. It is still stored in the `str` variable, while the `x` variable holds the newly-created substring. (Or if the original string's length was 20 characters or fewer, then both variables point to the same string instance.) – phoog May 27 '15 at 07:15
  • @phoog Are you sure it will point to the same instance if length is same? – Shaharyar May 27 '15 at 07:19
  • @Shaharyar i know i have str i dont have access to str because the customer gives me the substring over the phone or internet and i should get back the original string from Substring – amirtutunchi May 27 '15 at 07:19
  • @amirbt That is another scenario. We don't even know your system architecture/workflow. – Shaharyar May 27 '15 at 07:21
  • @Shaharyar I am, but that's an implementation detail, so you should not rely on it. See http://referencesource.microsoft.com/#mscorlib/system/string.cs,1270 – phoog May 27 '15 at 07:21
  • 1
    @Rahul, +1 for Math.Min(... I've been using if conditions to check for that. thanks. – yohannist May 27 '15 at 07:29
  • @Shaharyar i just want to get back the original str from substring and it is windows Form application is there anyway or i should try other things – amirtutunchi May 27 '15 at 07:42
-1

string a = "get the first 20 characters"; a = a.Substring(0, 20);