在给定字符串str的情况下,将字符串分为三部分,一个包含数字部分,一个包含字母部分,另一个包含特殊字符。
例子:
Input : geeks01for02geeks03!!!
Output :geeksforgeeks
010203
!!!
Here str = "Geeks01for02Geeks03!!!", we scan every character and
append in res1, res2 and res3 string accordingly.
Input : **Docoding123456789everyday##
Output :Docodingeveryday
123456789
**##
脚步 :
- 计算字符串的长度。
- 逐一扫描字符串的每个字符(ch)
- 如果(ch是数字),则将其附加到res1字符串。
- 否则,如果(ch是字母)附加在字符串res2中。
- 否则附加在字符串res3中。
- 打印所有字符串,我们将有一个字符串包含数字部分,其他非数字部分,最后一个包含特殊字符。
C++
// CPP program to split an alphanumeric
// string using STL
#include
using namespace std;
void splitString(string str)
{
string alpha, num, special;
for (int i=0; i= 'A' && str[i] <= 'Z') ||
(str[i] >= 'a' && str[i] <= 'z'))
alpha.push_back(str[i]);
else
special.push_back(str[i]);
}
cout << alpha << endl;
cout << num << endl;
cout << special << endl;
}
// Driver code
int main()
{
string str = "geeks01$$for02geeks03!@!!";
splitString(str);
return 0;
}
Java
// CPP program to split an alphanumeric
// string using stringbuffer
class Test
{
static void splitString(String str)
{
StringBuffer alpha = new StringBuffer(),
num = new StringBuffer(), special = new StringBuffer();
for (int i=0; i
Python3
# Python 3 program to split an alphanumeric
# string using STL
def splitString(str):
alpha = ""
num = ""
special = ""
for i in range(len(str)):
if (str[i].isdigit()):
num = num+ str[i]
elif((str[i] >= 'A' and str[i] <= 'Z') or
(str[i] >= 'a' and str[i] <= 'z')):
alpha += str[i]
else:
special += str[i]
print(alpha)
print(num )
print(special)
# Driver code
if __name__ == "__main__":
str = "geeks01$$for02geeks03!@!!"
splitString(str)
# This code is contributed by ita_c
C#
// C# program to split an alphanumeric
// string using stringbuffer
using System;
using System.Text;
class GFG {
// Function ot split string
static void splitString(string str)
{
StringBuilder alpha =
new StringBuilder();
StringBuilder num =
new StringBuilder();
StringBuilder special =
new StringBuilder();
for (int i = 0; i < str.Length; i++)
{
if (Char.IsDigit(str[i]))
num.Append(str[i]);
else if((str[i] >= 'A' &&
str[i] <= 'Z') ||
(str[i] >= 'a' &&
str[i] <= 'z'))
alpha.Append(str[i]);
else
special.Append(str[i]);
}
Console.WriteLine(alpha);
Console.WriteLine(num);
Console.WriteLine(special);
}
// Driver code
public static void Main()
{
string str = "geeks01$$for02geeks03!@!!";
splitString(str);
}
}
// This code is contributed by Sam007
Javascript
输出:
geeksforgeeks
010203
$$!@!!
上述解决方案的时间复杂度为O(n),其中n是字符串的长度。
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。