Baran Saeed
Baran Saeed

Reputation: 90

How to skip starting 2 words from a string in c#

How to ignore the first 2 words of a string

like:

String x = "hello world this is sample text";

in this the first two words are hello world, so i want to skip them, but next time maybe the words will not be the same, like maybe they become, "Hakuna Matata", but the program should also skip them.

P.S : don't not suggest remove characters it won't work here i guess, because we don't know what is the length of these words, we just want to skip the first two words. and print the rest.

Upvotes: 4

Views: 6652

Answers (3)

kat1330
kat1330

Reputation: 5332

Please try this code:

   String x = "hello world this is sample text";

   var y = string.Join(" ", x.Split(' ').Skip(2));

It will split string by spaces, skip two elements then join all elements into one string.

UPDATE:

If you have extra spaces than first remove extra spaces and remove words:

String x = "hello world this is sample text";
x =  Regex.Replace(x, @"\s+", " ");
var y = string.Join(" ", x.Split(' ').Skip(2));

UPDATE:

Also, to avoid extra spaces as suggested by Dai (in below comment) I used Split() with StringSplitOptions:

String x = "hello       world       this is      sample text";
var y = string.Join(" ", x.Split((char[])null, StringSplitOptions.RemoveEmptyEntries).Select(i => i.Trim()).Skip(2));

Upvotes: 7

Uniphonic
Uniphonic

Reputation: 865

Using a Regular Expression should do it:

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "hello world this is sample text";
      string pattern = @"(\w+\s+){2}(.*)";
      string replacement = "$1";
      Regex rgx = new Regex(pattern);
      string result = rgx.Replace(input, replacement);

      Console.WriteLine("Original String: {0}", input);
      Console.WriteLine("Replacement String: {0}", result);                             
   }
}

Upvotes: 0

Dai
Dai

Reputation: 155065

I don't recommend using IndexOf because it won't help you in the case of consecutive whitespace characters, and using String.Split(null) with String.Join is inefficient. You could do this using a regex or FSM parser:

Int32 startOfSecondWord = -1;

Boolean inWord = false;
Int32 wordCount = 0;
for( int = 0; i < input.Length; i++ ) {
    Boolean isWS = Char.IsWhitespace( input[i] );
    if( inWord ) {
        if( isWS ) inWord = false;
    }
    else {
        if( !isWS ) {
            inWord = true;
            wordCount++;

            if( wordCount == 2 ) {
                startOfSecondWord = i;
                break;
            }
        }
    }
}

if( startOfSecondWord > -1 ) return input.Substring( startOfSecondWord );

Upvotes: 0

Related Questions