Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I having a few problem for substring in C# as substring when value = null and substring the position you want in the string
Please help me to solve this problem! Thank so much !

What I have tried:

i have a paragraph code
C#
string str = "";
string str1 = "";
string str2 = "";
string str3 = "";
string str4 = "";
string str5 = "";
str = data2.SThe;
if (str != null)
{
    str1 = str.Substring(0, 3);
    str2 = str.Substring(3, 2);
    str3 = str.Substring(5, 2);
    str4 = str.Substring(7, 3);
    str5 = str.Substring(10);

    xrSTbhyt1.Text = str1;
    xrBHYT2.Text = str2;
    xrBHYT3.Text = str3;
    xrBHYT4.Text = str4;
    xrBHYT5.Text = str5;
}
else
{
    str = string.Empty;
}
Posted
Updated 9-Nov-20 2:35am
v2
Comments
[no name] 8-Nov-20 22:24pm    
"" is not the same as null (in case you were wondering); it's the same as string.Empty.

And your program will fail every time the length of data2.SThe is less than 11.
Huyyhaha 8-Nov-20 22:34pm    
Right! how does it not substring when the value is ""
PIEBALDconsult 9-Nov-20 8:34am    
Test the Length .

Generally, in cases like yours, if the value is null, you provide a default value. It seems your code already has it.

Alternative to your code:
C#
string str = "";
str = data2?.SThe;

// You can add this if you want 
//if(string.IsNullOrEmpty(str))
//  return;

// If null default to empty
xrSTbhyt1.Text = str?.Substring(0, 3) ?? "";;
xrBHYT2.Text = str?.Substring(3, 2) ?? "";;
xrBHYT3.Text = str?.Substring(5, 2) ?? "";;
xrBHYT4.Text = str?.Substring(7, 3) ?? "";;
xrBHYT5.Text = str?.Substring(10) ?? "";;

PS: As already pointed, this code is assuming the text length of 10 characters atleast. You should handle this usecase to avoid an error (if text returned is of shorter length)
 
Share this answer
 
v3
Comments
Huyyhaha 9-Nov-20 2:16am    
i was test it, it's ok with string.IsNullOrEmpty(str) also with
xrSTbhyt1.Text = str?.Substring(0, 3) ?? "";;
xrBHYT2.Text = str?.Substring(3, 2) ?? "";;
xrBHYT3.Text = str?.Substring(5, 2) ?? "";;
xrBHYT4.Text = str?.Substring(7, 3) ?? "";;
xrBHYT5.Text = str?.Substring(10) ?? "";;

not like that
The idea of defensive programming is to handle common errors in advance, and, it is based on the disturbing :) fact that there will be bugs ... yours, and the ones your end-users find with their unexpected behaviors. Better you should find them !

.NET/C# provide several facilities that handle common errors in accessing common data structures, parsing strings into numeric types, etc. These are expressed with function semantics like 'TryGetValue, 'TryParse, which perform some operation, and return a boolean indicating the operation's success or failure.

So, let's write a function with similar semantics to handle getting a substring:
using System;

namespace YourNameSpace
{
    public static class StringExtensions
    {
        public static bool TryGetSubString(this string str,  out string substring, uint start = 0, uint howmany = 0, bool dothrowerrors = false)
        {
            bool result = false;
            substring = null;

            if (string.IsNullOrEmpty(str))
            {
                if (dothrowerrors)
                {
                    throw new ArgumentException($"'{nameof(str)}' cannot be null or empty", nameof(str));
                }
                else
                {
                    return result;
                }
            }

            int len = str.Length - 1;

            if (howmany == 0 || start > len || start + howmany > len)
            {
                if (dothrowerrors)
                {
                    throw new ArgumentException($"'{nameof(str)}' is not long enough for these indexes", nameof(str));
                }
                else
                {
                    return result;
                }   
            }

            substring = str.Substring((int) start, (int) howmany);

            return true;
        }
    }
}
Notes:

1) by using type 'uint for the index/length parameters we prevent entering a negative int.

2) we are using the Extension method technique offered by C# >= 3.0 here

Use example:
private string test = "0123456";

// in some method or eventhandler
if (test.TryGetSubString(out string sresult, 5,1))
{
     // success: 'sresult contains "6"
}
else
{
     // fail: 'sresult contains "null   
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900