Home > Mobile >  How to count white space in a string based on other string
How to count white space in a string based on other string

Time:12-29

Suppose we have two string s1 and s2

s1 = "123    456 789 012 1234";
s2 = "1234567";

I want to print s2 with white space as given in string s1 . Output will be

Output = "123   456 7";

CodePudding user response:

Approach with simple for loop

string s1 = "123    456 789 012 1234";
string s2 = "1234567";

for (int i = 0; i < s1.Length && i < s2.Length; i  )
{
    if (char.IsWhiteSpace(s1[i]))
    {
        s2 = s2.Insert(i, s1[i].ToString());
    }
}

https://dotnetfiddle.net/POn5E2

CodePudding user response:

You should create a loop for s2 if the character equals s1 then add character to the result. Otherwise,until there add a space to result...

        string s1 = "123    456 789 012 1234";
        string s2 = "1234567";
        string result = "";

        int s1_index = 0;
        for (int i = 0; i < s2.Length; i  )
        {
            if (s1[s1_index] == ' ')
                while (s1[s1_index] == ' ')
                {
                    result  = ' ';
                    s1_index  ;
                }

            if (s2[i] == s1[s1_index])
                result  = s1[s1_index];

             s1_index  ;
    }

   Console.WriteLine(result);

CodePudding user response:

Split the s1 string into an array of substrings using the Split method, with the space character as the separator.

string[] s1Parts = s1.Split(' ');

Iterate through the elements of the s1Parts array, and for each element that is not empty, add the corresponding character from s2 to the output string.


for (int i = 0; i < s1Parts.Length; i  )
{
    if (!string.IsNullOrEmpty(s1Parts[i]))
    {
        output  = s2[i];
    }
}

Finally, print the output string to the console.

console.WriteLine(output);  // Outputs "123   456 7"

CodePudding user response:

Simply just put a condition on number of non-whitespace characters. Not efficient solution, but it has a good idea:

string s1 = "123    456 789 012 1234";
string s2 = "1234567";
var s2Length = s2.Length;

var array = s1.TakeWhile((c, index) => s1.Substring(0, index   1)
                                         .Count(f => !char.IsWhiteSpace(f)) <= s2Length)
              .ToArray();
var result = new string(array); //123    456 7
  •  Tags:  
  • c#
  • Related