Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Reduce multiple characters to one, in a string!

Reduce multiple characters to one, in a string!

Scheduled Pinned Locked Moved C#
tutorialhelp
14 Posts 6 Posters 16 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    Adeel Chaudhry
    wrote on last edited by
    #1

    Hello! Hope you all are doing great! Need suggestion of how to reduce multiple characters to 1! Example is as follows: We have a string str = "this is an example ! " we want to remove multiple space characters and want to have just single space instead! The number of spaces may be more than 200 in string! The result should be as follows: str = "this is an example ! " Any help/suggestion/guidence will certainly be appreciated!:)! Regards! Adeel --

    R G P A 4 Replies Last reply
    0
    • A Adeel Chaudhry

      Hello! Hope you all are doing great! Need suggestion of how to reduce multiple characters to 1! Example is as follows: We have a string str = "this is an example ! " we want to remove multiple space characters and want to have just single space instead! The number of spaces may be more than 200 in string! The result should be as follows: str = "this is an example ! " Any help/suggestion/guidence will certainly be appreciated!:)! Regards! Adeel --

      R Offline
      R Offline
      Rob Graham
      wrote on last edited by
      #2

      This should work:

      string oneSpace = " ";
      string twoSpaces = " ";
      string str = "You left out any multiple spaces in your example";
      string newStr = str.Replace(twoSpaces,oneSpace);

      L A 2 Replies Last reply
      0
      • R Rob Graham

        This should work:

        string oneSpace = " ";
        string twoSpaces = " ";
        string str = "You left out any multiple spaces in your example";
        string newStr = str.Replace(twoSpaces,oneSpace);

        L Offline
        L Offline
        Luc Pattyn
        wrote on last edited by
        #3

        Hi, since there may be more than 2 consecutive spaces, you need to iterate. This is how I do this:

        string s="whatever with many spaces";
        do {
        int len=s.Length;
        s=s.Replace(twoSpaces, oneSpace);
        } while (s.Length<len);

        For very long strings with many sequences of multiple spaces, it may be more economic to use a StringBuilder, and fill it in one pass using a bool that remembers whether last char added was a space or not. :)

        Luc Pattyn [My Articles]

        A R 2 Replies Last reply
        0
        • R Rob Graham

          This should work:

          string oneSpace = " ";
          string twoSpaces = " ";
          string str = "You left out any multiple spaces in your example";
          string newStr = str.Replace(twoSpaces,oneSpace);

          A Offline
          A Offline
          Adeel Chaudhry
          wrote on last edited by
          #4

          it is not working!!!:)! extra spaces can be of any number!! and this will only replace 2 spaces with 1 what if we have 99 spaces?:)!

          1 Reply Last reply
          0
          • L Luc Pattyn

            Hi, since there may be more than 2 consecutive spaces, you need to iterate. This is how I do this:

            string s="whatever with many spaces";
            do {
            int len=s.Length;
            s=s.Replace(twoSpaces, oneSpace);
            } while (s.Length<len);

            For very long strings with many sequences of multiple spaces, it may be more economic to use a StringBuilder, and fill it in one pass using a bool that remembers whether last char added was a space or not. :)

            Luc Pattyn [My Articles]

            A Offline
            A Offline
            Adeel Chaudhry
            wrote on last edited by
            #5

            :)! Thanks Luc, i guess i really have to learn to use stringbulder!:)! Thanks both of you!:)!

            1 Reply Last reply
            0
            • A Adeel Chaudhry

              Hello! Hope you all are doing great! Need suggestion of how to reduce multiple characters to 1! Example is as follows: We have a string str = "this is an example ! " we want to remove multiple space characters and want to have just single space instead! The number of spaces may be more than 200 in string! The result should be as follows: str = "this is an example ! " Any help/suggestion/guidence will certainly be appreciated!:)! Regards! Adeel --

              G Offline
              G Offline
              Guffa
              wrote on last edited by
              #6

              Please don't end every sentence with an exclamation mark. Those are used for interjections and exclamations, not for ordinary sentences. An ordinary sentence is ended by a period. You can replace multiple spaces using a regular expresson: str = Regex.Replace(str, " {2,}", " ");

              --- single minded; short sighted; long gone;

              A 1 Reply Last reply
              0
              • G Guffa

                Please don't end every sentence with an exclamation mark. Those are used for interjections and exclamations, not for ordinary sentences. An ordinary sentence is ended by a period. You can replace multiple spaces using a regular expresson: str = Regex.Replace(str, " {2,}", " ");

                --- single minded; short sighted; long gone;

                A Offline
                A Offline
                Adeel Chaudhry
                wrote on last edited by
                #7

                :)actually they were used for exclamations and that is because working and learning new things of c# do make me happy.

                P 1 Reply Last reply
                0
                • L Luc Pattyn

                  Hi, since there may be more than 2 consecutive spaces, you need to iterate. This is how I do this:

                  string s="whatever with many spaces";
                  do {
                  int len=s.Length;
                  s=s.Replace(twoSpaces, oneSpace);
                  } while (s.Length<len);

                  For very long strings with many sequences of multiple spaces, it may be more economic to use a StringBuilder, and fill it in one pass using a bool that remembers whether last char added was a space or not. :)

                  Luc Pattyn [My Articles]

                  R Offline
                  R Offline
                  Rob Graham
                  wrote on last edited by
                  #8

                  You are right, this would work better:

                          string test = "this  string   has    multiple    spaces      .";
                          StringBuilder sb = new StringBuilder(test);
                          int l1 = sb.Length;
                          int l2 = l1 +1;
                          while (l1 != l2)
                          {
                              l1 = sb.Length;
                              sb.Replace("  ", " ");
                              l2 = sb.Length;
                          }
                          string result = sb.ToString();
                  
                  L 1 Reply Last reply
                  0
                  • A Adeel Chaudhry

                    Hello! Hope you all are doing great! Need suggestion of how to reduce multiple characters to 1! Example is as follows: We have a string str = "this is an example ! " we want to remove multiple space characters and want to have just single space instead! The number of spaces may be more than 200 in string! The result should be as follows: str = "this is an example ! " Any help/suggestion/guidence will certainly be appreciated!:)! Regards! Adeel --

                    P Online
                    P Online
                    PIEBALDconsult
                    wrote on last edited by
                    #9

                    I happen to have one here, one I wrote in C many years ago and then ported to C# a few years back, thanks for giving me a reason to revisit it. (Now I'll revisit my Split that honors quotes and escapes as well.) Usage: subject = the string to compress trash = list of characters to compress (usually " \b" -- SPACE and TAB) replacements = what to replace them with (usually " " -- SPACE) quotes = if you don't want compress within quotes, specify "\"" or "'" escapes = not often used, but if for instance trash contains "n" and subject contains "\n" and you don't want it replaced, specify "\\" for escapes and the "\n" will be preserved (quotes and escapes may be empty or null) advanced: two characters may be specified for replacements (and I've forgotten why I allow it) given trash="z" and replacements="xy" then subject="zzz" becomes "yyx" (rather than "x") example:

                    if ( args.Length > 0 )
                    {
                    System.Console.Write
                    (
                    "<" +
                    PIEBALD.Lib.LibStr.Compress ( args [ 0 ] , " \b" , " " , "'" , "\\" )
                    + ">"
                    ) ;
                    }

                    /**************************************************************************************************************/
                    /* Compress sequences of "trash" characters down to one */

                        public static string
                        Compress
                        (
                            string subject      ,
                            string trash        ,
                            string replacements ,
                            string quotes       ,
                            string escapes
                        )
                        {
                            System.Text.StringBuilder result = new System.Text.StringBuilder ( subject.Length ) ;
                    
                            char prevch = '\\0' ;
                            int  index  = 0    ;
                            int  quo    = -1   ;
                            int  quoon  = -1   ;
                            int  escon  = -1   ;
                    
                            if ( quotes == null )
                            {
                                quotes = "" ;
                            }
                    
                            if ( escapes == null )
                            {
                                escapes = "" ;
                            }
                    
                            while ( index < subject.Length )
                            {
                                if ( ( escon = escapes.IndexOf ( prevch ) ) != -1 )
                                {
                                    quoon = -1 ;
                                }
                                else
                                {
                                    quoon = quotes.IndexOf ( subject \[ index \] ) ;
                                }
                    
                                if ( quoon != -1 )
                                {
                                    if ( qu
                    
                    A 1 Reply Last reply
                    0
                    • P PIEBALDconsult

                      I happen to have one here, one I wrote in C many years ago and then ported to C# a few years back, thanks for giving me a reason to revisit it. (Now I'll revisit my Split that honors quotes and escapes as well.) Usage: subject = the string to compress trash = list of characters to compress (usually " \b" -- SPACE and TAB) replacements = what to replace them with (usually " " -- SPACE) quotes = if you don't want compress within quotes, specify "\"" or "'" escapes = not often used, but if for instance trash contains "n" and subject contains "\n" and you don't want it replaced, specify "\\" for escapes and the "\n" will be preserved (quotes and escapes may be empty or null) advanced: two characters may be specified for replacements (and I've forgotten why I allow it) given trash="z" and replacements="xy" then subject="zzz" becomes "yyx" (rather than "x") example:

                      if ( args.Length > 0 )
                      {
                      System.Console.Write
                      (
                      "<" +
                      PIEBALD.Lib.LibStr.Compress ( args [ 0 ] , " \b" , " " , "'" , "\\" )
                      + ">"
                      ) ;
                      }

                      /**************************************************************************************************************/
                      /* Compress sequences of "trash" characters down to one */

                          public static string
                          Compress
                          (
                              string subject      ,
                              string trash        ,
                              string replacements ,
                              string quotes       ,
                              string escapes
                          )
                          {
                              System.Text.StringBuilder result = new System.Text.StringBuilder ( subject.Length ) ;
                      
                              char prevch = '\\0' ;
                              int  index  = 0    ;
                              int  quo    = -1   ;
                              int  quoon  = -1   ;
                              int  escon  = -1   ;
                      
                              if ( quotes == null )
                              {
                                  quotes = "" ;
                              }
                      
                              if ( escapes == null )
                              {
                                  escapes = "" ;
                              }
                      
                              while ( index < subject.Length )
                              {
                                  if ( ( escon = escapes.IndexOf ( prevch ) ) != -1 )
                                  {
                                      quoon = -1 ;
                                  }
                                  else
                                  {
                                      quoon = quotes.IndexOf ( subject \[ index \] ) ;
                                  }
                      
                                  if ( quoon != -1 )
                                  {
                                      if ( qu
                      
                      A Offline
                      A Offline
                      Adeel Chaudhry
                      wrote on last edited by
                      #10

                      :)! that is some re-usability!:)! the suggestion/guidence by Luc is proving to be great and actually bit simpler tooo ;) Thanks PIEBALDconsult :)

                      P 1 Reply Last reply
                      0
                      • A Adeel Chaudhry

                        :)! that is some re-usability!:)! the suggestion/guidence by Luc is proving to be great and actually bit simpler tooo ;) Thanks PIEBALDconsult :)

                        P Online
                        P Online
                        PIEBALDconsult
                        wrote on last edited by
                        #11

                        I don't like to write single-use library functions, the more flexibility the better in my opinion, but the RegularExpression solution may be our best bet.

                        1 Reply Last reply
                        0
                        • R Rob Graham

                          You are right, this would work better:

                                  string test = "this  string   has    multiple    spaces      .";
                                  StringBuilder sb = new StringBuilder(test);
                                  int l1 = sb.Length;
                                  int l2 = l1 +1;
                                  while (l1 != l2)
                                  {
                                      l1 = sb.Length;
                                      sb.Replace("  ", " ");
                                      l2 = sb.Length;
                                  }
                                  string result = sb.ToString();
                          
                          L Offline
                          L Offline
                          Luc Pattyn
                          wrote on last edited by
                          #12

                          Sorry, but taking the trouble of using StringBuilder only makes sense if you succeed in avoiding unnecessary copy operations, hence StringBuilder.Replace is not my choice at all. Either you use String.Replace in a loop, or a one-pass populating StringBuilder. BTW your initial values for i1 and i2 are not needed if you test after the loop (do-while). :)

                          Luc Pattyn [My Articles]

                          1 Reply Last reply
                          0
                          • A Adeel Chaudhry

                            :)actually they were used for exclamations and that is because working and learning new things of c# do make me happy.

                            P Online
                            P Online
                            PIEBALDconsult
                            wrote on last edited by
                            #13

                            If you're happy and you know it keep it to your own darn self.

                            1 Reply Last reply
                            0
                            • A Adeel Chaudhry

                              Hello! Hope you all are doing great! Need suggestion of how to reduce multiple characters to 1! Example is as follows: We have a string str = "this is an example ! " we want to remove multiple space characters and want to have just single space instead! The number of spaces may be more than 200 in string! The result should be as follows: str = "this is an example ! " Any help/suggestion/guidence will certainly be appreciated!:)! Regards! Adeel --

                              A Offline
                              A Offline
                              AFSEKI
                              wrote on last edited by
                              #14

                              str = str.Replace(" ", " "); the first argument in str.Replace is a 2 white space characters ( press spacebar twice ) the second argument in str is a 1 white space character ( press spacebar once ) Sorry, but I had to explain these arguments ion details, they are not correctly shown after the message is posted. Hope this helps...

                              1 Reply Last reply
                              0
                              Reply
                              • Reply as topic
                              Log in to reply
                              • Oldest to Newest
                              • Newest to Oldest
                              • Most Votes


                              • Login

                              • Don't have an account? Register

                              • Login or register to search.
                              • First post
                                Last post
                              0
                              • Categories
                              • Recent
                              • Tags
                              • Popular
                              • World
                              • Users
                              • Groups