Чтобы сократить имя с помощью строки в C, вы можете использовать различные методы. Вот несколько подходов:
Метод 1: использование первой буквы каждого слова
#include <stdio.h>
#include <string.h>
void abbreviateName(char* name) {
int length = strlen(name);
char abbreviation[length];
int abbreviationIndex = 0;
abbreviation[abbreviationIndex++] = name[0]; // Add the first character
for (int i = 0; i < length; i++) {
if (name[i] == ' ') { // Check for space
abbreviation[abbreviationIndex++] = name[i + 1]; // Add the next character after space
}
}
abbreviation[abbreviationIndex] = '\0'; // Add the null terminator
printf("Abbreviated name: %s\n", abbreviation);
}
int main() {
char name[] = "John Doe";
abbreviateName(name);
return 0;
}
Выход:
Abbreviated name: JD
Метод 2: использование инициалов
#include <stdio.h>
#include <string.h>
void abbreviateName(char* name) {
int length = strlen(name);
char abbreviation[length];
int abbreviationIndex = 0;
abbreviation[abbreviationIndex++] = name[0]; // Add the first character
for (int i = 0; i < length; i++) {
if (name[i] == ' ') { // Check for space
abbreviation[abbreviationIndex++] = name[i + 1]; // Add the next character after space
}
}
abbreviation[abbreviationIndex] = '\0'; // Add the null terminator
printf("Abbreviated name: %s\n", abbreviation);
}
int main() {
char name[] = "John Doe";
abbreviateName(name);
return 0;
}
Выход:
Abbreviated name: JD
Метод 3. Использование разделителя
#include <stdio.h>
#include <string.h>
void abbreviateName(char* name, char delimiter) {
int length = strlen(name);
char abbreviation[length];
int abbreviationIndex = 0;
abbreviation[abbreviationIndex++] = name[0]; // Add the first character
for (int i = 0; i < length; i++) {
if (name[i] == delimiter) {
abbreviation[abbreviationIndex++] = name[i + 1]; // Add the next character after the delimiter
}
}
abbreviation[abbreviationIndex] = '\0'; // Add the null terminator
printf("Abbreviated name: %s\n", abbreviation);
}
int main() {
char name[] = "John-Doe-Smith";
abbreviateName(name, '-');
return 0;
}
Выход:
Abbreviated name: JDS