Trimming /null values from string after converting from char[] (in C#) - c#

There is an array of characters e.g.
char [] biggerText = new char [8];
then I input some values likewise:
biggerText[0] = (char) 12;
biggerText[1] = (char) 48;
then I use the following operation:
string smallerText= string.Join("", biggerText);
and when you perform smallerText.Length you get 8 and NOT 2.
What is the most effective method to trim this array to omit the null values when converting to string?

Why don't you use a List<char>? This way, you don't have to worry about indexes, and you don't have to know the final length at the beginning (as pointed out in the comment by #n8wrl).
var list = new List<char>();
list.Add((char)12);
list.Add((char)48);
Then you can get the final string in a more elegant way:
var smallerText = new string(list.ToArray());
And this string will have the correct Length.

This should do the trick.
string smallerText = string.Join("", biggerText.Where(n => n != '\0'));
This is a good way to do it, because Trim will work just with white spaces and may not work well for you.

You can make a new string from the array and trim the null chars from the end:
string smallerText = new String(biggerText).TrimEnd('\0');

You can use TakeWhile to only take the characters until you see a "null" character assuming you don't want any of the characters that might exist after the first "null" character.
string smallerText= string.Join("", biggerText.TakeWhile(c => c != '\0'));

char [] biggerText = new char [8];
biggerText[0] = (char)12;
biggerText[1] = (char)48;
string smallerText= new string(biggerText).Replace("\0", string.Empty);
int length = smallerText.Length;
\0 can be at any location, so just replace it with empty value.

If you mean the most efficient:
string smallerText = new string(biggerText, 0, 2);
but "the most effective method to trim" is the .Trim method 😊
string smallerText = new string(biggerText).TrimEnd(char.MinValue);

Related

Substring IndexOf in c#

I have a string that looks like this: "texthere^D123456_02". But I want my result to be D123456.
this is what i do so far:
if (name.Contains("_"))
{
name = name.Substring(0, name.LastIndexOf('_'));
}
With this I remove at least the _02, however if I try the same way for ^ then I always get back texthere, even when I use name.IndexOf("^")
I also tried only to check for ^, to get at least the result:D123456_02 but still the same result.
I even tried to name.Replace("^" and then use the substring way I used before. But again the result stays the same.
texthere is not always the same length, so .Remove() is out of the question.
What am I doing wrong?
Thanks
When call Substring you should not start from 0, but from the index found:
String name = "texthere^D123456_02";
int indexTo = name.LastIndexOf('_');
if (indexTo < 0)
indexTo = name.Length;
int indexFrom = name.LastIndexOf('^', indexTo - 1);
if (indexFrom >= 0)
name = name.Substring(indexFrom + 1, indexTo - indexFrom - 1);
string s = "texthere^D123456_02";
string result= s.Substring(s.IndexOf("^") + 1);//Remove all before
result = result.Remove(result.IndexOf("_"));//Remove all after
Use the String.Split method :
var split1 = name.Split('^')[1];
var yourText = split1.Split('_')[0];
Or you could use RegExp to achieve basically the same.
Your easiest solution would be to split the string first, and then use your original solution for the second part.
string name = "texthere^D123456_02";
string secondPart = name.Split('^')[1]; // This will be D123456_02
Afterwards you can use the Substring as before.
With Regular Expression
string s = "texthere^D123456_02";
Regex r1 = new Regex(#"\^(.*)_");
MatchCollection mc = r1.Matches(s);
Console.WriteLine("Result is " + mc[0].Groups[1].Value);
An alternative to what's already been suggested is to use regex:
string result = Regex.Match("texthere^D123456_02", #"\^(.*)_").Groups[1].Value; // D123456
use regex.
Regex regex = new Regex(#"\^(.*)_");
Match match = regex.Match(name);
if(match.Success)
{
name= match.Groups[1].Value
}
An easier way would be to use Split
string s = "texthere^D123456_02";
string[] a = s.Split('^', '_');
if (a.Length == 3) // correct
{
}
Well, if you use the same code you posted, it's doing the right thing, you start to retrieve characters from the char 0 and stop when it finds "^", so what you will get is "texthere".
If you want only the value, then use this:
name = name.Substring(0, name.LastIndexOf('_')).Substring(name.IndexOf("^") + 1);
It will first remove whatever is after the "_" and whatever is before "^".
Substring takes a position and a length, so you need to actually figure out where your caret position is and where the underscore is to calculate the length
var name = "texthere^D123456_02";
if(name.Contains('_'))
{
var caretPos = name.IndexOf('^') + 1; // skip ahead
var underscorePos = name.IndexOf('_');
var length = underscorePos - caretPos;
var substring = name.Substring(caretPos, length);
Debug.Print(substring);
};
Try this and let me know how it goes
string inputtext = "texthere^D123456_02";
string pattern = #".+\^([A-Z]+[0-9]+)\_[0-9]+";
string result = Regex.Match(inputtext, pattern).Groups[1].Value;
String name = "texthere^D123456_02"
print name.split('_', '^')[1]
This splits your string at all occurrences of _ and ^ and returns the list of strings after the split. Since the string you need D123456 would be at the 1st index, (i.e. the 2nd position), I have printed out that.
If you are just wanting the "d123456" it's simple with just String.Split() there is no need for anything else. Just define the index you want afterwards. There are overloads on Split() for this very reason.
//...
var source = "texthere^D123456_02";
var result = source.Split(new char[] {'^', '_'}, StringSplitOptions.RemoveEmptyEntries)[1];
Console.WriteLine(result);
//Outputs: "D123456"
Hope this helps.

Replacing specific parts of a string in an array

I'm pretty familiar with finding and replacing things in an array, but I'm having trouble finding out how to replace specific parts of a string. For instance, say the first item in my array is a string of sixteen random numbers like 1786549809654768. How would I go about replacing the first twelve characters with x's for example?
Because string can be translated to and from an array of char you could easily transform your problem into replace things in an array problem:
char[] characters = input.ToCharArray();
// do your replace logic here
string result = new string(characters);
Or you could use Substring. Assuming n is number of characters you want to replace from the beginning or the string:
string result = new string('x', n) + input.Substring(n);
You can use Linq:
String test = "1234123412341234";
string output = new String(test.Select((c, index) => index < 12 ? 'x' : c).ToArray());
Console.WriteLine(output);
//xxxxxxxxxxxx1234

How to extract specific number in a string surrounded by numbers and text C#

I am trying to extract specific number in a string with a format of "Q23-00000012-A14" I only wanted to get the numbers in 8 digit 00000000 the 12.
string rx = "Q23-00000012-A14"
string numb = Regex.Replace(rx, #"\D", "");
txtResult.Text = numb;
But im getting the result of 230000001214, I only want to get the 12 and disregard the rest. Can someone guide me.
If your string are always in this format (numbers are covered with "-"), I suggest useing string.split()
string rx = "Q23-00000012-A14"
string numb = int.parse(rx.Split('-')[1]).ToString();//this will get 12 for you
txtResult.Text = numb;
It's an easier way than using regex
Edit!! When you use rx.split('-') , it break string into array of strings with value of splited texts before and after '-'
So in this case:
rx.Split('-')[0]= "Q23"
rx.Split('-')[1]= "00000012"
rx.Split('-')[2]= "A12"
So you shouldn't use Replace. Use Match instead.
string pattern = #"[A-Z]\d+-(\d+)-[A-Z]\d+" ;
var regex = new Regex(pattern);
var match = regex.Match("Q23-00000012-A14");
if (match.Success)
{
String eightNumberString = match.Groups[1].Value; // Contains "00000012"
int yourvalueAsInt = Convert.ToInt32(eightNumberString) ; // Contains 12
}
Why you use don't simply substring or split function ?
string rx = "Q23-00000012-A14";
// substring
int numb = int.Parse(rx.Substring(5, 8));
// or split
int numb = int.Parse(rx.Split('-')[1]);
txtResult.Text = numb.ToString();
(I think it's a better way to use split method because if you change your constant 'Q23' length the method still work)

best possible way to get given substring

lets say I have string in format as below:
[val1].[val2].[val3] ...
What is the best way to get the value from the last bracket set [valx] ?
so for given example
[val1].[val2].[val3]
the result would be val3
You have to define best first, best in terms of readability or cpu-cycles?
I assume this is efficient and readable enough:
string values = "[val1].[val2].[val3]";
string lastValue = values.Split('.').Last().Trim('[',']');
or with Substring which can be more efficient, but it's not as safe since you have to handle the case that's there no dot at all.
lastValue = values.Substring(values.LastIndexOf('.') + 1).Trim('[',']');
So you need to check this first:
int indexOflastDot = values.LastIndexOf('.');
if(indexOflastDot >= 0)
{
lastValue = values.Substring(indexOflastDot + 1).Trim('[',']');
}
For a quick solution to your problem (so not structural),
I'd say:
var startIndex = input.LastIndexOf(".["); // getting the last
then using the Substring method
var value = input.Substring(startIndex + 2, input.Length - (startIndex - 2)); // 2 comes from the length of ".[".
then removing the "]" with TrimEnd function
var value = value.TrimEnd(']');
But this is by all means not the only solution, and not structural to apply.. Just one of many answers to your problem.
I think you want to access the valx.
The easiest solution that comes in my mind is this one:
public void Test()
{
var splitted = "[val1].[val2].[val3]".Split('.');
var val3 = splitted[2];
}
You can use following:
string[] myStrings = ("[val1].[val2].[val3]").Split('.');
Now you can access via index. For last you can use myStrings[myStrings.length - 1]
Providing, that none of val1...valN contains '.', '[' or ']' you can use a simple Linq code:
String str = #"[val1].[val2].[val3]";
String[] vals = str.Split('.').Select((x) => x.TrimStart('[').TrimEnd(']')).ToArray();
Or if all you want is the last value:
String str = #"[val1].[val2].[val3]";
String last = str.Split('.').Last().TrimStart('[').TrimEnd(']');
I'm assuming you always need the last brace. I would do it like this:
string input = "[val1].[val2].[val3]";
string[] splittedInput = input.split('.');
string lastBraceSet = splittedInput[splittedInput.length-1];
string result = lastBraceSet.Substring(1, lastBraceSet.Length - 2);
string str = "[val1].[val2].[val3]";
string last = str.Split('.').LastOrDefault();
string result = last.Replace("[", "").Replace("]", "");
string input="[val1].[val2].[val3]";
int startpoint=input.LastIndexOf("[")+1;
string result=input.Substring(startpoint,input.Length-startpoint-1);
I'd use the below regex. One warning is that it won't work if there are unbalanced square brackets after the last pair of brackets. Most of the answers given suffer from that though.
string s = "[val1].[val2].[val3]"
string pattern = #"(?<=\[)[^\]]+(?=\][^\[\]]*$)"
Match m = Regex.Match(s, pattern)
string result;
if (m.Success)
{
result = m.Value;
}
I would use regular expression, as they are the most clear from intention point of view:
string input = "[val1].[val2].[val3] ...";
string match = Regex.Matches(input, #"\[val\d+\]")
.Cast<Match>()
.Select(m => m.Value)
.Last();

C# how to pick out certain part in a string

I have a string in a masked TextBox that looks like this:
123.456.789.abc.def.ghi
"---.---.---.---.---.---" (masked TextBox format when empty, cannot use underscore X( )
Please ignore the value of the characters (they can be duplicated, and not unique as above). How can I pick out part of the string, say "789"? String.Remove() does not work, as it removes everything after the index.
You could use Split in order to separate your values if the . is always contained in your string.
string input = "123.456.789.abc.def";
string[] mySplitString = input.Split('.');
for (int i = 0; i < mySplitString.Length; i++)
{
// Do you search part here
}
Do you mean you want to obtain that part of the string? If so, you could use string.Split
string s = "123.456.789.abc.def.ghi";
var splitString = s.Split('.');
// splitString[2] will return "789"
You could simply use String.Split (if the string is actually what you have shown)
string str = "123.456.789.abc.def.ghi";
string[] parts = str.Split('.');
string third = parts.ElementAtOrDefault(2); // zero based index
if(third != null)
Console.Write(third);
I've just used Enumerable.ElementAtOrDefault because it returns null instead of an exception if there's no such index in the collection(It falls back to parts[2]).
Finding a string:
string str="123.456.789.abc.def.ghi";
int i = str.IndexOf("789");
string subStr = str.Substring(i,3);
Replacing the substring:
str = str.Replace("789","").Replace("..",".");
Regex:
str = Regex.Replace(str,"789","");
The regex can give you a lot of flexibility finding things with minimum code, the drawback is it may be difficult to write them
If you know the index of where your substring begins and the length that it will be, you can use String.Substring(). This will give you the substring:
String myString = "123.456.789";
// looking for "789", which starts at index 8 and is length 3
String smallString = myString.Substring(8, 3);
If you are trying to remove a specific part of the string, use String.Replace():
String myString = "123.456.789";
String smallString = myString.Replace("789", "");
var newstr = new String(str.where(c => "789")).tostring();..i guess this would work or you can use sumthng like this
Try using Replace.
String.Replace("789", "")

Categories

Resources