The task is as follows: to develop a program in the C++ language, using a null terminal string (a null-terminated string) to represent the text in the program, and C language tools to perform operations on this string. The program receives a sentence consisting of words separated by commas or spaces. Among the words of this sentence, finds words made up of the same letters as the first word. Move the found words to the beginning of the sentence.
I've been sitting for hours trying to figure out how pointers and functions work to perform operations on a C-style string, with no success. The last idea that came to my mind is to simply insert the words that consist of the letters of the first word of the original string at the beginning of a new string, and the rest of the words at the end of this line.
char* shiftWords(char* str) {
char tempAnsStr[100] = "";
char* tempStr;
char* word1;
char* nextStr;
bool notnull = false;
word1 = strtok(str, ", ");
tempStr = strtok(NULL, ", ");
while (tempStr) {
if (!(check(word1, tempStr))) {
if (notnull) {
if (strlen(nextStr) != 0) {
strcat(tempAnsStr, tempStr);
}
}
else {
strcpy(tempAnsStr, tempStr);
notnull = true;
}
}
strcat(tempStr, tempAnsStr);
strcpy(tempAnsStr, tempStr);
tempStr = strtok(NULL, ", ");
}
return tempAnsStr;
}
bool check(char* A, char* B)
{
if (strlen(A) == strlen(B)) {
int letters_A[1024];
char temp;
for (int i = 0; i < strlen(A); i++) {
letters_A[i] = int(A[i]);
}
for (int i = 0; i < strlen(A) - 1; i++) {
for (int j = 0; j < strlen(A) - i - 1; j++) {
if (letters_A[j] > letters_A[j + 1]) {
temp = letters_A[j];
letters_A[j] = letters_A[j + 1];
letters_A[j + 1] = temp;
}
}
}
int letters_B[1024];
for (int i = 0; i < strlen(B); i++) {
letters_B[i] = int(B[i]);
}
for (int i = 0; i < strlen(B) - 1; i++) {
for (int j = 0; j < strlen(B) - i - 1; j++) {
if (letters_B[j] > letters_B[j + 1]) {
temp = letters_B[j];
letters_B[j] = letters_B[j + 1];
letters_B[j + 1] = temp;
}
}
}
bool tf = true;
for (int i = 0; i < strlen(A); i++) {
if (letters_A[i] != letters_B[i]) {
tf = false;
break;
}
}
return tf;
}
return false;
}