How to split a string in half but not in the middle of a word with C#

1 Answer

0 votes
using System;

public class Program
{
	public static void Main(string[] args)
	{
		string str = "c# c java c++ python go";

		string halfstr = str.Substring(0, (str.Length / 2 + 1));
		int center = halfstr.LastIndexOf(' ') + 1;

		string[] parts = new string[] {str.Substring(0, center), str.Substring(center)};

		Console.WriteLine(parts[0]);
		Console.WriteLine(parts[1]);
	}
}





/*
run: 
     
c# c java 
c++ python go
     
*/

 



answered Aug 9, 2023 by avibootz
edited Sep 10, 2024 by avibootz
...