tags:

views:

156

answers:

7

Hi all,

I need help in trimming everything in my string till end after it encounters the first "\0"

So:

"test\1\2\3\0\0\0\0\0\0\0\0\0_asdfgh_qwerty_blah_blah_blah"

becomes

"test\1\2\3"

I am using c#. Help would be greatly appreciated.

Thanks.

+5  A: 

How about:

string s = "test\1\2\3\0\0\0\0\0\0\0\0\0_asdfgh_qwerty_blah_blah_blah";

int offset = s.IndexOf("\\0");
if (offset >= 0)
    s = s.Substring(0, offset);
egrunin
What if input string doesn't contain such substring? It will throw an Exception
abatishchev
s = s.Substring(0, Math.Max(0,s.IndexOf("\\0"));
Ryan Emerle
That's incorrect too, since the second argument to `Substring` is the length. You'd want `Math.Max(s.Length, s.IndexOf("\\0")`.
Daniel DiPaolo
@abatishchev: more than he asked for, but sure.
egrunin
+4  A: 
if (someString.Contains("\\0"))
    someString = someString.Substring(0, someString.IndexOf("\\0"));
Anthony Pegram
What would happen if you didn't have "if" in there? would you get the same string back that you were searching????
VoodooChild
@VoodooChild: `IndexOf` will return -1 if original string doesn't contain substring and this will break `Substring`
abatishchev
@Anthony: Also you can use `(@"\0")` to make code more readable
abatishchev
@abatishchev, I'm aware, but someone else may not be. Thank you.
Anthony Pegram
A: 
String.Substring(0, String.IndexOf("\0"))
Jaymz
+1  A: 

Find the position of the first occurrence of "\0" and make another string which is a substring of you original from start to the position of the first occurrence.

VoodooChild
I better get an up vote for the thoughtful explanation instead of just throwing the answer up on the board lol....
VoodooChild
A: 
if (origString.IndexOf(@"\0") != -1) {
   newString = origString.Substring(0, origString.IndexOf(@"\0");
} else {
    newString = origString;
}
Daniel DiPaolo
I see I'm the only one who took into account the case where there is no `\0` in the string :)
Daniel DiPaolo
A: 

The match value returned by the following regex should be what you're after as well (as alternative to the substring method), basically it begins at the string start and as long as the next two characters aren't \0 it expands the match:

^(?:(?!=\0).)+
Lucero
A: 

somestring=Regex.split(somestring,"\\0")[0];

VeeArr