Getting portion of string

  • Thread starter Thread starter RP
  • Start date Start date
R

RP

I have a string in the following format

Computer [comp]

I want to remove the text that starts with [. Though I used substring
which keeps checking whether the character is [ and stops reading more
characters. I want to know is there any built-in function for this
that is both fast and easy to use.
 
RP said:
I have a string in the following format

Computer [comp]

I want to remove the text that starts with [. Though I used substring
which keeps checking whether the character is [ and stops reading more
characters. I want to know is there any built-in function for this
that is both fast and easy to use.

google:
http://www.google.com/search?source=ig&hl=nl&rlz=&q=csharp+substring&meta=

1st link:
http://en.csharp-online.net/Manipulating_Strings_in_CSharp—Finding_a_Substring_within_a_String
(because you're obviously tooo lazy to start Google in the 1st place...)
 
if you only want to get the string before '['. try ...

string str = "Computer[comp]";
str = str.Substring(0, str.IndexOf("["));

if there are multiple "[]" in your string try this.

string str = "Comp[cooom] makes [power] one cry";
string[] array = str.Split(']');
string finishedString = string.Empty;
foreach (string member in array)
{
if (member.Contains("["))
finishedString += member.Substring(0, member.IndexOf("["));
else
finishedString += member;
}



Regards,

RP said:
I have a string in the following format
Computer [comp]
I want to remove the text that starts with [. Though I used substring
which keeps checking whether the character is [ and stops reading more
characters. I want to know is there any built-in function for this
that is both fast and easy to use.

google:http://www.google.com/search?source=ig&hl=nl&rlz=&q=csharp+substring&...

1st link:http://en.csharp-online.net/Manipulating_Strings_in_CSharp—Fi...
(because you're obviously tooo lazy to start Google in the 1st place...)
 
I have a string in the following format

Computer [comp]

I want to remove the text that starts with [. Though I used substring
which keeps checking whether the character is [ and stops reading more
characters. I want to know is there any built-in function for this
that is both fast and easy to use.

I don't think there is any built in String functionality.
You might try this:

string str = "Comp[cooom] makes [power] one cry";
while (str.IndexOf('[') >= 0 || str.IndexOf(']') >= 0)
{
int start = str.IndexOf("[");
int end = str.IndexOf("]");
str = str.Remove(start, (end - start + 1));
}
Console.WriteLine(str);

Depending on the size of the string, you might consider using the
StringBuilder class.

Regards,
Greg
 
Back
Top