Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to break a string into columns of words and align to right with C

1 Answer

0 votes
#include <stdio.h>

void align_string(const char* str, char alignment) {
	int col, i;
	int width[512] = { 0 };
	const char* s;

	for (s = str, i = col = 0; s[i]; s += i + 1) {
		for (i = 0; s[i] && s[i] != '~' && s[i] != '\n'; i++);

		if (i > width[col]) width[col] = i;

		if (col++ >= 512) return;

		if (s[i] == '\n') col = 0;

		if (!s[i]) break;
	}

	int l = 0, r = 0;

	for (s = str, i = col = 0; s[i]; s += i + 1) {
		for (i = 0; s[i] && s[i] != '~' && s[i] != '\n'; i++);

		switch (alignment) {
		case 'l':	r = width[col] - i; break;
		case 'c':	r = (width[col] - i) / 2; break;
		case 'r':	r = 0; break;
		}

		l = width[col++] - i - r + 1;

		while (l--) putchar(' ');
		printf("%.*s", i, s);
		while (r--) putchar(' ');

		if (s[i] != '~') {
			putchar('\n');
			col = 0;
		}
		if (!s[i]) break;
	}
}

int main(void)
{
	const char* str =
		"C~R~C#~C++~Go~Java~Python~Rust~Dart~VB~Pascal~\n"
		"JavaScript~Swift~PHP~Fortran~SQL~Kotlin~MATLAB~Swift~Ruby~Simula~COBOL~\n"
		"Scala~ALGOL~Amiga E~Delphi~Elixir~F~Assembly~JavaFX~LINQ~\n"
		"NodeJS~TypeScript~Modula~Objective-C";

	align_string(str, 'r');

	return 0;
}





/*
run:

		  C          R      C#         C++     Go   Java   Python   Rust Dart     VB Pascal
 JavaScript      Swift     PHP     Fortran    SQL Kotlin   MATLAB  Swift Ruby Simula  COBOL
	  Scala      ALGOL Amiga E      Delphi Elixir      F Assembly JavaFX LINQ
	 NodeJS TypeScript  Modula Objective-C

*/

 



answered Nov 5, 2022 by avibootz
edited Nov 5, 2022 by avibootz
...