如何旋转字符串 [英] How to rotate strings
本文介绍了如何旋转字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个单词,我需要旋转它直到第一个元音。例如:声望 - > estigepr。
Suppose I have a word and I need to rotate it until the first vowel. For example: prestige --> estigepr.
for (i = 0; i < length; i++)
{
switch (word[i])
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("%s", word);
break;
}
我该怎么办?当word [i] =元音时,循环应该停止。如果没有元音,则整个单词都会旋转;即单词没有改变。
How can I do it? The loop should stop when word[i] = vowel. If there are no vowels, the whole word is rotated; i.e. the word isn't changed.
推荐答案
有很多方法可以做到这一点。
其中一种方法是:创建一个循环的单链表并记住字符串的长度,比如说N.这样,如果你选择下一个N,指向任何元素的指针将为你提供旋转字母的序列。元素。如果您还记得原始指针,请回到它,再向前一次迭代到下一个字母并选择另外N个元素,您将有下一次旋转字符串。重复这个班次N - 1次,你获得所有的旋转。
-SA
There can be many ways to do this.
One of the ways is: create a circular singly-linked list and remember the length of the string, say, N. This way, a pointer to any of the elements will give you the sequence of "rotated" letters if you pick next N elements. If you remember the original pointer, get back to it, to one iteration forward to next letter and pick another N elements, you will have next rotation of the string. Repeat this shift N − 1 times, and you obtain all the rotations.
—SA
以下内容:
How about the following:
char buf[BUFSIZE];
strncpy(buf, "...", BUFSIZE-1);
buf[BUFSIZE-1] = '\0';
size_t len = length(buf);
size_t i = 0;
while(i < len && !is_vowel(buf[i])) i++;
if (i < len) rotate(buf, i);
is_vowel(...)
和 rotate(...)
留作练习。
干杯
Andi
is_vowel(...)
and rotate(...)
is left as exercise.
Cheers
Andi
您可以使用以下代码: -
You can use the following code:-
#include<stdio.h>
#include<string.h>
int main(){
char str[100],rtStr[100];
int len,i,flag=0,vowel_pos,c=0;
printf("Enter the string: ");
scanf("%s",&str);
for(i=0;i<strlen(str);i++){>
if(str[i]=='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' || str[i]=='u' || str[i]=='A' || str[i]=='E' || str[i]=='I' || str[i]=='O' || str[i]=='U'){
vowel_pos=i;
flag=1;
break;
}
}
//Vawel is found and string will be arrange
if(flag==1){
while (c < (strlen(str)-vowel_pos)) {
rtStr[c] = str[vowel_pos+c];
c++;
}
for(i=0;i<vowel_pos;i++){>
rtStr[c]=str[i];
c++;
}
rtStr[c] = '\0';
printf("Rotate String is: %s",rtStr);
}
//Vawel is not found, so the string will be unchanged
else{
printf("Rotate String is: %s",str);
}
return 0;
}
这篇关于如何旋转字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文