taking a character out of a string

Wyverex wyverex.cypher at gmail.com
Mon Aug 18 15:58:24 PDT 2008


Michael P. wrote:
> Okay, so what I'm trying to do is read in 2 phrases, then use 2 foreach loops to check for spaces and remove them.
> Example:
> 
> foreach( character; phraseOne )
> {
>    if ( character == ' ' )
>    {
>       take the character out of the string ( and resize it??? )
>    }
> }
> foreach( character; phraseTwo )
> {
>    if ( character == ' ' )
>    {
>       take the character out of the string ( and resize it??? )
>    }
> }
> 
> Also, is there anyway I can use only 1 foreach loop to do those 2 things? I'm pretty sure when I repeat code like that there must be a better way.
> 
> And 1 thing about readln and readf: I realized that I can't use readf to read words with spaces. And when there is a space entered with readf, the other words stay in the input buffer.(input buffer is what it is, right?) Then when I use readln (maybe readf too, I didn't check that), it automatically enters what was left over. How do I flush the input buffer?
> Thanks.
> -Michael P.


Try taking advantage of slicing.. havn't tested this but should be close..

char[] strip( char[] str, char c, uint index = 0 )
{
   for(int i = index; i < str.length; i++)
       if(str[i] == c)
          return str[0..i] ~ strip( str[i+1..$], c, i+1 );

   return str;
}


More information about the Digitalmars-d-learn mailing list