I am trying to loop through a string and look for a character and join every character after said character.
string info = "0 1 2 3 4 5 F->data 95753 info ";
for(int i =0; i < info.length; i )
{
if(info[i] == 'F')
{
// join all characters after 'F' Result = "0 1 2 3 4 5 F->data95753info"
}
The Output should be : 0 1 2 3 4 5 F->data95753info
CodePudding user response:
Using Linq you can do something like this
String.Join('F',info.Split('F').Select((s,i)=>i==0?s:s. Replace(" ","")))
CodePudding user response:
Instead of looping through the string, use String.IndexOf()
and String.Substring()
to split your string in half, then use String.Replace()
to remove all of the spaces.
Once you have both halves of the string correct, concatenate them.
Example:
string info = "I want to remove the spaces after this: there are no spaces here.";
int index = info.IndexOf(':');
string part1 = info.Substring(0, index);
string part2 = info.Substring(index).Replace(" ", "");
Console.WriteLine (part1 part2);
CodePudding user response:
string info = "0 1 2 3 4 5 F->data 95753 info ";
int indexofF = info.IndexOf('F');
string replacement = $"{info.Substring(0,indexofF 1)}{info.Substring(indexofF 1).Replace(" ",string.Empty)}";
- find the index of the character you want to process with
- take string on either side of it using substrings
- replace the spaces on right side
CodePudding user response:
Here's the easiest way:
string info = "0 1 2 3 4 5 F->data 95753 info ";
string output = Regex.Replace(info, @"(?<=F.*)\s", "");
That gives me 0 1 2 3 4 5 F->data95753info
.
This is just a look behind regular expression replacement.
CodePudding user response:
Use string "replace".
string replacement = info.Replace('F', 'S');
Console.WriteLine( replacement);